PHP Application Development With ADODB (part 1) By icarus July 24, 2002 Printed from DevShed.

com URL: http://www.devshed.com/Server_Side/PHP/ADODB/ADODB1 Any Port In A Storm As a developer, one of the most important things to consider when developing a Web application is portability. Given the rapid pace of change in the Web world, it doesn't do to bind your code too tightly to a specific operating system, RDBMS or programming language; if you do, you'll find yourself reinventing the wheel every time things change on you (and they will - take my word for it). That's where this article comes in. Over the course of this two-part tutorial, I'm going to be showing you how to make your code a little more portable, by using a database abstraction layer for all your RDBMS connectivity. This database abstraction layer allows you to easily switch between one RDBMS and another, without requiring either a code rewrite or a long, tortuous retest cycle. In the long run, this will save you time, save your customers money, and maybe make your life a little simpler. Before we get started, one caveat: while portability is something you should strive for regardless of which language or platform you work on, it's impossible to cover every single possibility in this article...and I don't plan to. Instead, I'll be restricting myself to my favourite Web programming language, PHP, and the ADODB database abstraction library, also written in PHP. Similar libraries exist for most other programming languages, and you should have no trouble adapting the techniques in this article to other platforms. Let's get started! This article copyright Melonfire 2000-2002. All rights reserved. A Little Insulation First up, let's get the lingo straight: what the heck is a database abstraction library anyway? If you've worked with different databases, you've probably seen that each database operates in a slightly different manner from the others. The data types aren't always uniform, and many of them come with proprietary extensions (transactions, stored procedures et al) that aren't supported elsewhere. Additionally, the API to interact with these databases is not uniform; PHP itself comes with a different API for each supported database type, For all these reasons, switching from one database to another is typically a complex process, one which usually involves porting data from one system to another (with the assorted datatyping complications), rewriting your code to use the new database API, and testing it to make sure it all works. And that's where a database abstraction layer can help.

Typically, a database abstraction layer functions as a wrapper around your code, exposing a set of generic methods to interact with a database server. These generic methods are internally mapped to the native API for each corresponding database, with the abstraction layer taking care of ensuring that the correct method is called for your selected database type. Additionally, most abstraction layers also incorporate a generic superset of datatypes, which get internally converted into datatypes native to the selected RDBMS. In order to better understand the difference, consider the following diagram:

As you can see, without an abstraction layer in place, you need to use a different API call for each of the three database types. With an abstraction layer in place, however, you can transparently use a single, generic call, and have the abstraction layer convert it into the native API call. A number of different abstraction layers are available for PHP, most notably the PEAR DBI, Metabase and PHPLib. The one I'm going to use in this article is named ADODB (Active Data Objects DataBase), and it's one of the most full-featured and efficient PHP abstraction libraries available today. Developed by John Lim, the library currently supports a wide variety of database systems, including MySQL, PostgreSQL, Oracle, Interbase, Microsoft SQL Server, Access, ODBC and others, and has been used in a number of well-known open-source PHP projects, including phpLens, PostNuke and Webodex. You can download a copy of ADODB from http://php.weblogs.com/adodb - get your copy now, set it up, and flip the page for an example of how it can be used. This article copyright Melonfire 2000-2002. All rights reserved. The Bookworm Turns Before we get into the code, you might want to take a quick look at the database table I'll be using throughout this article. Here it is:

mysql> SELECT * FROM library; +----+-------------------+----------------+ | id | title | author | +----+-------------------+----------------+ | 14 | Mystic River | Dennis Lehane | | 15 | For Kicks | Dick Francis | | 16 | XML and PHP | Vikram Vaswani | | 17 | Where Eagles Dare | Jack Higgins | +----+-------------------+----------------+

As you might have guessed, the "library" table contains a list of all the books currently taking up shelf space in my living room. Each record within the table is

"john".Dick Francis XML and PHP . ?> Here's what the output looks like: Mystic River .identified by a unique number (the geek term for this is "foreign key".Dennis Lehane For Kicks . } // get and print number of rows in resultset echo "\n[" . Since PHP comes with out-of-the-box support for MySQL. // execute query $query = "SELECT * FROM library".$row[2]\n". let's suppose I want to display a list of my favourite books on my personal Web site. accomplishing this is almost as simple as it sounds. "doe") or die ("Unable to connect!"). // iterate through rows and print column data // in the form TITLE . <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). Everything I need is stored in the table above. all yours truly has to do is write a script to pull it out and massage it into a readable format. " . Now. but you can forget that one immediately). // close database connection mysql_close($connection). // open connection to database $connection = mysql_connect("localhost".AUTHOR while ($row = mysql_fetch_row($result)) { echo "$row[1] . mysql_error()). // select database mysql_select_db("db278") or die ("Unable to select database!").Jack Higgins . $result = mysql_query($query) or die ("Error in query: $query.Vikram Vaswani Where Eagles Dare . " rows returned]\n". mysql_num_rows($result) .

} . execute a query. or an object (whose properties correspond to the column names) with mysql_fetch_object(). The example above uses the mysql_fetch_row() function to retrieve each row as an integer-indexed array. Which is where the database abstraction layer comes in. // create an object instance // configure it for a MySQL connection $db = NewADOConnection("mysql"). $result = $db->Execute($query) or die("Error in query: $query. "db278") or die("Unable to connect!"). "doe". This article copyright Melonfire 2000-2002. // include the ADODB library include("adodb. retrieve the result and iterate through it.[4 rows returned] The process here is fairly straightforward: connect to the database.AUTHOR while (!$result->EOF) { echo $result->fields[1] . however." .php"). // execute query $query = "SELECT * FROM library". The problem with this script? Since I've used MySQL-specific functions to interact with the database. // open connection to database $db->Connect("localhost". $result->MoveNext(). "\n".inc. Anatomy Class In order to demonstrate how the abstraction layer works. with the array indices corresponding to the column numbers in the resultset. $db->ErrorMsg()). it's just as easy to retrieve each row as an associative array (whose keys correspond to the column names) with mysql_fetch_assoc(). it's going to crash and burn the second I switch my data over to PostgreSQL or Oracle.take a look: <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). // iterate through resultset // print column data in format TITLE . "john". $result->fields[2] . All rights reserved. I'll use it to rewrite the previous example . " . " .

The first step is. since it uses the ADODB abstraction library.php"). as above. ?> The parameter passed to the object constructor tells ADODB which type of database you're trying to connect to. <? // include the ADODB library include("adodb. 2. you could just as easily use "pgsql" or "oci8" or. This is accomplished via the Connect() method.inc. however. since I'm going to be connecting to a MySQL database server. Next. a quick explanation of the functions used above: 1. ?> This output of this snippet is equivalent to that of the previous one. I've used the argument "mysql". // close database connection $db->Close().. it's time to open up a connection to the database. I'll show you how in a minute . and it will invoke the appropriate drivers or additional classes as required. Next. In this case. You don't need to worry about including each and every one. obviously. there are over thirty different files included with the library.in fact. which must be passed a set of connection parameters. create an instance of the ADODB class. ?> Note that the ADODB library doesn't consist of just this file . many of them drivers for different databases. to interact with the database server. " rows returned]\n". to include the abstraction layer in your script. . it holds out the promise of continuing to work no matter which database I use. $result->RecordCount() . 3. <? // create an object instance // configure library for a MySQL connection $db = NewADOConnection("mysql"). rather than PHP's native API. simply include the main class file.but first.// get and print number of rows in resultset echo "\n[" ..

the line of code above attempts to open up a connection to the MySQL database named "db278". "john". ?> Reading this may make your head hurt. 4. . to iterate through the returned resultset and display individual fields (these individual fields are accessed as array elements of the object's "fields" property). } ?> In this case. ?> Successful query execution returns a new object containing the results of the query. the object's Execute() method can be used to execute SQL queries on that database. "\n". $result->MoveNext(). Once the Connect() method does its job. The result object returned in the previous step exposes methods and properties that can be used to extract specific fields or elements from the returned resultset. $db->ErrorMsg()).AUTHOR while (!$result->EOF) { echo $result->fields[1] . Note the special ErrorMsg() method.<? // open connection to database $db->Connect("localhost". the object's MoveNext() method is used. with the username "john" and password "doe". " . $result = $db->Execute($query) or die("Error in query: $query. but there *is* method to the madness roughly translated. This data is then printed to the output device. <? // execute query $query = "SELECT * FROM library". "db278") or die("Unable to connect!"). "doe"." . <? // iterate through resultset // print column data in format TITLE . which can be used to obtain the last error message generated by the system. on the host named "localhost". " . 5. $result->fields[2] . in combination with a "while" loop.

with all the heavy lifting done. Everything else would stay exactly the same. allowing them to write one piece of code that can be used in different situations. " rows returned]\n". For example. $result->RecordCount() . Which translates into simpler.Once all the rows in the resultset have been processed. you can retrieve the resultset as a string-indexed associative array. .inc. with a new database type. ?> 6.it exposes a generic API to developers. // include the ADODB library include("adodb. <? // get and print number of rows in resultset echo "\n[" . <? // close database connection $db->Close(). Different Strokes ADODB also offers a number of alternative methods to process a resultset.a new argument would need to be passed to the object constructor. ?> In the event that someone (maybe even me) decides to switch to a different database. with all the ugly bits hidden away and handled internally. Finally. which demonstrates: <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). where the keys are field names and the values are the corresponding field values. cleaner code. This is the beauty of an abstraction layer . the object's RecordCount() method is used to print the number of rows in the resultset. All rights reserved. Simple. and my code would continue to work exactly as before. the Close() method is used to gracefully close the database connection and disengage from the database. better script maintainability. the only change required in the script above would be to the line instantiating the connection object . Consider the following example.php"). huh? This article copyright Melonfire 2000-2002. shorter development cycles and an overall Good Feeling.

$result = $db->Execute($query) or die("Error in query: $query. ?> In this case.// create an object instance // configure library for a MySQL connection $db = NewADOConnection("mysql"). // create an object instance // configure library for a MySQL connection . // iterate through resultset // print column data in format TITLE . $result->fields['author'] . $db->ErrorMsg()). "john". whose properties correspond to the field names. $result->RecordCount() . via ADODB's FetchNextObject() method. } // get and print number of rows in resultset echo "\n[" . "doe". $result->MoveNext(). "\n". <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). // open connection to database $db->Connect("localhost". " .php"). // get resultset as associative array $ADODB_FETCH_MODE = ADODB_FETCH_ASSOC. // include the ADODB library include("adodb. " . // execute query $query = "SELECT * FROM library". You can also fetch each row as an object. the value of the special $ADODB_FETCH_MODE variable tells ADODB how the resultset should be structured." . " rows returned]\n". // close database connection $db->Close().AUTHOR while (!$result->EOF) { echo $result->fields['title'] . "db278") or die("Unable to connect!").inc.

inc. // open connection to database $db->Connect("localhost". "john". and does not require an explicit call to MoveNext(). " .$db = NewADOConnection("mysql"). } // get and print number of rows in resultset echo "\n[" . the method returns false. // close database connection $db->Close(). which demonstrates: <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). This array can then be processed with a simple "foreach" or "for" loop. // include the ADODB library include("adodb. // execute query $query = "SELECT * FROM library". ?> Note that this FetchNextObject() method automatically moves to the next row in the resultset. Consider the following example.php"). Getting It All You can replace the Execute() method with the GetAll() method. " . This article copyright Melonfire 2000-2002. . " rows returned]\n". "\n". "db278") or die("Unable to connect!")." .AUTHOR while ($row = $result->FetchNextObject()) { echo $row->TITLE . $result = $db->Execute($query) or die("Error in query: $query. $db->ErrorMsg()). which returns the complete resultset as a two-dimensional array of field-value pairs. All rights reserved. $row->AUTHOR . "doe". $result->RecordCount() . // create an object instance // configure library for a MySQL connection $db = NewADOConnection("mysql"). Once the end of the resultset is reached. // iterate through resultset // print column data in format TITLE .

AUTHOR foreach ($result as $row) { echo $row[1] . $row[2] . "\n". the GetAll() method creates a two-dimensional array of result data. "doe". // clean up $db->Close(). " rows returned]\n". "db278") or die("Unable to connect!"). // print_r($result). // execute query $query = "SELECT * FROM library".// open connection to database $db->Connect("localhost". sizeof($result) . $db->ErrorMsg()). $result = $db->GetAll($query) or die("Error in query: $query. ?> In this case. Array ( [0] => Array ( [0] => 14 [id] => 14 [1] => Mystic River [title] => Mystic River [2] => Dennis Lehane [author] => Dennis Lehane ) [1] => Array ( [0] => 15 [id] => 15 [1] => For Kicks [title] => For Kicks . " ." . "john". // iterate through resultset // print column data in format TITLE . which looks something like this. } // get and print number of rows in resultset echo "\n[" . // uncomment the following line to see the returned array. " .

The size of the array is equivalent to the total number of rows in the resultset. and so on . which return the number of rows and columns in the recordset respectively.[2] => Dick Francis [author] => Dick Francis ) [2] => Array ( [0] => 16 [id] => 16 [1] => XML and PHP [title] => XML and PHP [2] => Vikram Vaswani [author] => Vikram Vaswani ) ) . // include the ADODB library include("adodb. "john". The most useful of these are the RecordCount() and FieldCount() methods.. This article copyright Melonfire 2000-2002. // create an object instance // configure library for a MySQL connection $db = NewADOConnection("mysql"). Here's a simple example. which demonstrates: <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). This array can then be iterated over by a "foreach" loop. . rather than one row at a time. and the required values accessed as regular array elements. especially in situations when you would prefer to have the entire recordset available at once. "doe". Playing The Field ADODB comes with a number of utility functions that provide you with useful information on the query you just executed. "db278") or die("Unable to connect!"). // open connection to database $db->Connect("localhost".... All rights reserved. This method provides a useful alternative to the Execute() method.php").inc.

// execute query $query = "SELECT * FROM library". // execute query $query = "SELECT * FROM library". } // clean up $db->Close(). $result = $db->Execute($query) or die("Error in query: $query. // create an object instance // configure library for a MySQL connection $db = NewADOConnection("mysql"). // get field information for($x=0. "john". $result = $db->Execute($query) or die("Error in query: $query. // get and print number of fields in resultset echo $result->FieldCount() . " . // open connection to database $db->Connect("localhost". ?> You can obtain further information on each field with the FetchField() method. " fields returned\n". $x<$result->FieldCount(). $x++) { print_r($result->FetchField($x)). $db->ErrorMsg()). including its name and type. // get and print number of rows in resultset echo $result->RecordCount() . which returns an object containing detailed information on the field properties. " rows returned\n". " . // clean up $db->Close(). "doe". "db278") or die("Unable to connect!"). which might make this a little clearer: <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). $db->ErrorMsg()). . // include the ADODB library include("adodb. Consider the following variant of the example above.php").inc.

you can obtain the last auto-increment ID generated via ADODB's Insert_ID() method. // include the ADODB library include("adodb.php"). // open connection to database . Strange Relationships In case you're performing an INSERT query on a table containing an auto-increment primary key. All rights reserved.inc.?> Here's what the output might look like for the "id" field: stdClass Object ( [name] => id [table] => library [def] => [max_length] => 3 [not_null] => 1 [primary_key] => 1 [multiple_key] => 0 [unique_key] => 0 [numeric] => 1 [blob] => 0 [type] => int [unsigned] => 1 [zerofill] => 0 [binary] => ) This article copyright Melonfire 2000-2002. <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). // create an object instance // configure library for a MySQL connection $db = NewADOConnection("mysql").

author) VALUES ($title. $result = $db->Execute($query) or die("Error in query: $query. $db->ErrorMsg()).php"). Luser'". "john". either by adding. $db->Insert_ID(). the Affected_Rows() method can come in handy to tell you the number of rows affected. Luser"). " . If you're executing a query that affects the table. "john". It's You!"). $query = "INSERT INTO library (title. } // clean up $db->Close(). // open connection to database $db->Connect("localhost". deleting or modifying rows. // create an object instance // configure library for a MySQL connection $db = NewADOConnection("mysql"). which comes in handy when you need to escape special characters in your query string. "doe". // execute query $title = $db->qstr("It's Not Me.$db->Connect("localhost". "db278") or die("Unable to connect!"). $author = $db->qstr("J. // include the ADODB library include("adodb. " . $result = $db->Execute($query) or die("Error in query: $query. $author)". // return number of affected rows if ($result) . <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). "doe". // print auto-generated ID if ($result) { echo "Last inserted ID is " . ?> Note also the qstr() method.inc. $db->ErrorMsg()). "db278") or die("Unable to connect!"). // execute query $query = "DELETE FROM library WHERE author = 'J.

// iterate through resultset while (!$result->EOF) { echo $result->fields[1] . // execute query // get 5 rows. // create an object instance // configure library for a MySQL connection $db = NewADOConnection("mysql"). "db278") or die("Unable to connect!"). $result->fields[2] . All rights reserved. " . "\n". } // clean up $db->Close(). $db->ErrorMsg()). "john". // open connection to database $db->Connect("localhost". // include the ADODB library include("adodb. 3) or die("Error in query: $query.inc. } // clean up $db->Close(). $result = $db->SelectLimit($query.php"). 5. starting from row 3 $query = "SELECT * FROM library". "doe". " rows deleted". <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). " . ?> .{ echo $db->Affected_Rows() . $result->MoveNext(). Hitting The Limit The SelectLimit() method can be used to restrict the number of rows retrieved." . ?> This article copyright Melonfire 2000-2002.

In this case. <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). } // clean up $db->Close(). ?> . The first argument to the method is the query to execute. the second is the number of rows required. "db278") or die("Unable to connect!"). } // get table list echo "\nTables in current database:\n". "doe". // create an object instance // configure library for a MySQL connection $db = NewADOConnection("mysql"). you can obtain a list of databases on the server via the MetaDatabases() method. // open connection to database $db->Connect("localhost".php"). // include the ADODB library include("adodb. // get database list echo "Databases:\n".inc. "john". Finally. foreach($db->MetaTables() as $table) { echo "* $table\n". and the third is the row offset from which to begin. foreach($db->MetaDatabases() as $d) { echo "* $d\n". the SelectLimit() method can be used to obtain a subset of the complete resultset retrieved from the database. and a list of tables within the current database via the MetaTables() method.

0. retrieving database. Examples are illustrative only.This article copyright Melonfire 2000-2002. and escaping special characters prior to inserting them into a database..be good! Note: All examples in this article have been tested on Linux/i586 with PHP 4. when I'll be exploring things like transactions. Until then. All rights reserved. Coming Soon.2. explaining how it could be used to insulate your code from the impact of a database change and thereby add portability to your PHP application. I demonstrated a number of useful utility functions. I showed you the different methods the ADODB library provides to iterate over a resultset. most notably functions related to counting rows and columns. I demonstrated the basics of the ADODB database abstraction library. constitutes just the tip of the ADODB iceberg . Finally.12 and ADODB 2. and to convert a resultset into native PHP arrays suitable for further processing.. All this. Over the preceding pages. of course. Tune in next week for the advanced course. To A Screen Near You And that's about it for this introductory tutorial. YMMV! .there's a lot more to this library than meets the eye.2. cached queries. Melonfire provides no warranties or support for the source code described in this article. and are not meant for a production environment. Apache 1. data typing and dynamic menus. table and field information.3.0.

"doe". 2002 Printed from DevShed. // open connection to database $db->Connect("localhost". and let's get started! This article copyright Melonfire 2000-2002. // include the ADODB library include("adodb. // prepare query $query = $db->Prepare("INSERT INTO library (title. // create an object instance // configure library for a MySQL connection $db = NewADOConnection("mysql").php"). which demonstrates: <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). Over the next few pages.the ADODB class comes with two methods that can save you a huge amount of time and also reduce overhead. ADODB comes with a whole bunch of bells and whistles. All rights reserved. Rapid Execution In the event that you need to execute a particular query multiple times with different values . which allow you to do some fairly nifty new things in your PHP scripts. ?)").for example. "john".so flip the page. that isn't all she wrote. I'll be showing you some of them . Consider the following example. "db278") or die("Unable to connect!"). and showed you a little of how it works. a series of INSERT statements . I introduced you to the ADODB database abstraction library.com/Server_Side/PHP/ADODB/ADODB2 Moving On In the first part of this article. and also gave you a crash course in the basic functions built into the library.PHP Application Development With ADODB (part 2) By icarus July 31.devshed. .inc.com URL: http://www. author) VALUES (?. I demonstrated how using it in your PHP application development could substantially reduce the time spent on code rewrites if your RDBMS decided to change shape. Fortunately.

All rights reserved. only simulated functionality is available and Prepare() becomes equivalent to a simple Execute().". ?> The Prepare() function. However. readies a query for execution. with no inherent performance gain. this benefit is only available to you if your database system supports prepared queries (MySQL does not at this time. // iterate through each line in file foreach ($data as $l) { // split on comma $arr = explode(". $db->ErrorMsg()). array($arr[0].// read title-author list in from CSV file $data = file("list. It should be noted that using Prepare() can provide performance benefits when you have a single query to be executed a large number of times with different values.these placeholders are replaced by actual values each time Execute() runs on the prepared statement. which actually executes the query (bzzzt!). although Interbase and Oracle do). " . Note the two placeholders used in the query string passed to Prepare() . you'll be pleased to hear that ADODB allows you to transparently use this feature in your scripts. but quite a few others do). The second argument to Execute() is a PHP array containing the values to be substituted in the query string. $l). prepare() returns a handle to the prepared query. The following example demonstrates: <?php // uncomment this to see plaintext output in your browser .txt"). which is stored and then passed to the Execute() method. in all other cases. A Fear Of Commitment If your database system supports transactions (MySQL doesn't. // insert values into prepared query $result = $db->Execute($query. Instead. } // clean up $db->Close. which takes an SQL query as parameter. $arr[1])) or die("Error in query: $query. This article copyright Melonfire 2000-2002. but does not execute it (kinda like the priest that walks down the last mile with you to the electric chair).

"john". // first query $query = "INSERT INTO library (title.99')". "doe". $db->ErrorMsg()).php"). price) VALUES ($id. $query = "INSERT INTO purchase_info (id. // turn off auto-commit // begin transaction block $db->BeginTrans(). $result = $db->Execute($query) or die("Error in query: $query. } // clean up $db->Close.// header("Content-Type: text/plain"). // open connection to database $db->Connect("localhost". // create an object instance // configure library for a MySQL connection $db = NewADOConnection("mysql"). you can go ahead and execute as many queries as you . " . via the BeginTrans() method. author) VALUES ('Title A'. 'USD 39. // use ID from first query in second query if ($result) { $id = $db->Insert_ID(). one which can be ended by either CommitTrans() or RollbackTrans(). ?> The first step here is to turn off auto-committal of data to the database. $db->ErrorMsg()). } // else rollback else { $db->RollbackTrans(). "db278") or die("Unable to connect!"). 'Author B')". } // if no failures if ($result) { // commit $db->CommitTrans(). Once autocommit has been turned off. " .inc. this method also marks the beginning of a transaction block. $result = $db->Execute($query) or die("Error in query: $query. // include the ADODB library include("adodb.

$result = $db->Execute($query) or die("Error in query: $query. Why? Because caching your queries can result in a fairly significant performance improvement. // include the ADODB library include("adodb. Cache Cow One of the coolest things about ADODB has to be its support for cached queries.php"). and used to determine whether or not the entire transaction should be committed. " . .AUTHOR while (!$result->EOF) { echo $result->fields[1] . Every call to Execute() within the transaction block returns either a true or false value." . $result->RecordCount() . " . $db->ErrorMsg()). // create an object instance // configure it for a MySQL connection $db = NewADOConnection("mysql"). especially if you're executing the same tired old SELECT every time.like. "doe". " rows returned]\n". Once you're sure that all is well. you can rewind gracefully with the RollbackTrans() function. // iterate through resultset // print column data in format TITLE . "\n". $result->fields[2] . In order to illustrate the difference. "db278") or die("Unable to connect!"). These values can be tracked. All rights reserved. secure in the knowledge that no changes have (yet) been made to the database. } // get and print number of rows in resultset echo "\n[" . depending on whether or not the query was successful. "john".inc. $result->MoveNext(). This article copyright Melonfire 2000-2002. In the event that you realize you made a mistake. // open connection to database $db->Connect("localhost". you can save your data to the database via a call to the CommitTrans() method. // execute query $query = "SELECT * FROM library". let's take a look at how this normally works: <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain").

"doe".$query) or die("Error in query: $query. and you were getting 5000 hits a minute. // create an object instance // configure it for a MySQL connection $db = NewADOConnection("mysql"). // include the ADODB library include("adodb.it's a very basic SQL SELECT operation with ADODB. " . "\n". you'd be running the query above 30. // execute query $query = "SELECT * FROM library".php"). "john"." . As you might imagine. and using this cached resultset in each subsequent run of the query.AUTHOR while (!$result->EOF) { echo $result->fields[1] . ?> This should be familiar to you by now . If this was your personal Web site. $result->MoveNext(). $db->ErrorMsg()). $result = $db->CacheExecute(300. ADODB offers a better option . and can also provide you with an incremental performance benefit.inc. $result->fields[2] . " . this will have your database server scurrying around like a hamster on cocaine . } .000 times an hour. // iterate through resultset // print column data in format TITLE . // open connection to database $db->Connect("localhost".caching the results of the first SELECT query. Here's what the revised script looks like: <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain").'. // set cache location $ADODB_CACHE_DIR = '. "db278") or die("Unable to connect!").not to mention affecting the performance of your Web site.// close database connection $db->Close(). This reduces the load on the database server.

// create an object instance // configure it for a MySQL connection $db = NewADOConnection("mysql").inc.a cached resultset is processed in exactly the same manner as a non-cached one. All rights reserved. One of the most useful is the GetMenu() method. // execute query $query = "SELECT title. when the items in the various form listboxes have to be dynamically built from a database. "doe". the second is. "db278") or die("Unable to connect!"). and uses it to automatically build a form drop-down list containing the database records. // print HTML menu . "john". This comes in very handy for dynamicallygenerated forms. which retrieves and iterates over a resultset. You can also use the CacheFlush() method to flush all queries from the cache. obviously. " rows returned]\n". // open connection to database $db->Connect("localhost". What's On The Menu? ADODB also comes with a couple of methods designed specifically for common Web development tasks. The remainder of the script remains unchanged . ?> The first argument to CacheExecute() is the number of seconds to cache the query results. // close database connection $db->Close().// get and print number of rows in resultset echo "\n[" . " . $result->RecordCount() . $db->ErrorMsg()). the query string itself. $result = $db->Execute($query) or die("Error in query: $query. id FROM library".php"). This article copyright Melonfire 2000-2002. Here's an example of how it works: <html> <head></head> <body> <?php // include the ADODB library include("adodb.

or even an HTML table. The GetMenu() method can simplify the task of developing a Web form substantially. the third lets you specify whether the first item in the list should be empty. ?> </body> </html> The GetMenu() method takes a number of arguments. the contents of the list box are built from the resultset returned by the query. The first argument is the name for the list ("library". // close database connection $db->Close().. while the second is the corresponding value. Here's the HTML code generated by the script above: <select name="library" > <option value="15">Mystic River</option> <option value="16">Where Eagles Dare</option> <option value="17">XML and PHP</option> </select> As you can see. which can be used to control the behaviour of the generated list box.. ADODB also allows you to export a resultset into a variety of different formats comma-separated text. tab-separated text. in this case). These functions are not part of the ADODB class per se. . The following example demonstrates: <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). and the fourth lets you control whether or not the list allows multiple selection.print $result->GetMenu("library".consider using it the next time you need to build a list box from the records in a database. All rights reserved. the first column of the resultset becomes the label for each list item. ''. rather. which needs to include()-d in your scripts. A Rose By Any Other Name. they are packaged as ancillary functions in a separate file. This article copyright Melonfire 2000-2002. significantly reducing the amount of code you have to write . the second is the default value for the list. false).

like this: <?php // snip // return a CSV string echo rs2csv($result. "db278") or die("Unable to connect!"). // execute query $query = "SELECT title. ?> . "john". id FROM library". $db->ErrorMsg()). // open connection to database $db->Connect("localhost".15 Where Eagles Dare. " . // include conversion functions include("toexport. "doe".// include the ADODB library include("adodb.inc. false). $result = $db->Execute($query) or die("Error in query: $query.php").php").17 You can suppress the first line . // return a CSV string echo rs2csv($result).by adding an extra argument to the call to rs2csv(). // create an object instance // configure it for a MySQL connection $db = NewADOConnection("mysql").inc. ?> Here's the output: title.id Mystic River.16 XML and PHP.the column list . // close database connection $db->Close().

// close database connection $db->Close(). "john". // return a tab-separated string echo rs2tab($result). // include conversion functions include("toexport.16 XML and PHP. $db->ErrorMsg()).php"). // execute query $query = "SELECT title. id FROM library". "doe". $result = $db->Execute($query) or die("Error in query: $query. // include the ADODB library include("adodb. "db278") or die("Unable to connect!").17 You can format the data as a tab-separated string with the rs2tab() function.15 Where Eagles Dare.inc.inc. // open connection to database $db->Connect("localhost".php"). // create an object instance // configure it for a MySQL connection $db = NewADOConnection("mysql"). " . ?> which returns the following output: .And here's the revised output: Mystic River. <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain").

inc. // close database connection $db->Close(). $db->ErrorMsg()). $result = $db->Execute($query) or die("Error in query: $query. "db278") or die("Unable to connect!"). // execute query $query = "SELECT title. // open connection to database $db->Connect("localhost". ?> </body> </html> which looks like this: . "doe". <html> <head></head> <body> <?php // uncomment this to see plaintext output in your browser // header("Content-Type: text/plain"). id FROM library".php"). // include conversion functions include("tohtml.php"). // include the ADODB library include("adodb. // create an object instance // configure it for a MySQL connection $db = NewADOConnection("mysql"). "john". " .inc. // return a table echo rs2html($result).titleid Mystic River15 Where Eagles Dare16 XML and PHP17 or as an HTML table with the rs2html() function.

improve performance by caching query results. Examples are illustrative only.A number of other interesting conversion functions are also shipped with ADODB take a look at the documentation for more information. That isn't all. Melonfire provides no warranties or support for the source code described in this article. commit and roll back transactions. at http://php. and the PHP community at large.2.com/ADOdb_manual MySQL and ADODB. at http://php.weblogs.com/adodb_tutorial Tips on writing portable SQL. I showed you the fundamentals executing queries.ADODB comes with a wealth of features.weblogs. illustrating how ADODB could be used to optimize multiple-run queries.0. See you soon! Note: All examples in this article have been tested on Linux/i586 with PHP 4. at http://php.12 and ADODB 2. and how you can use it in your own PHP projects. YMMV! .com/portable_sql Web services with ADODB. I introduced you to the ADODB database abstraction class and demonstrated how it could be used in your Web development efforts.weblogs. For more information on what it can do. take a look at the following links: The ADODB home page. though . iterating over resultsets. All rights reserved. obtaining table and row information and then moved on to more advanced material. and automatically write HTML (or text) files. I'm outta here. and is constantly being improved by its author. and are not meant for a production environment.0.weblogs.com/ADODB The ADODB manual. The Final Countdown And that's about it for the moment.2. Over the course of this two-part article.weblogs. Apache 1.com/adodb_csv As for me. at http://php. This article copyright Melonfire 2000-2002.3. at http://php.

Sign up to vote on this title
UsefulNot useful