HomePHP Page 5 - PHP Application Development With ADODB (part 2)
What's On The Menu? - PHP
In this concluding article, find out about ADODB's advancedfunctions, with examples that demonstrate how ADODB can be used tooptimize multiple-run queries, commit and roll back transactions,improve performance by caching query results, and automatically writeHTML (ortext) files.
ADODB also comes with a couple of methods designed specifically for common Web development tasks. One of the most useful is the GetMenu() method, which retrieves and iterates over a resultset, and uses it to automatically build a form drop-down list containing the database records. This comes in very handy for dynamically-generated forms, when the items in the various form listboxes have to be dynamically built from a database.
Here's an example of how it works:
// include the ADODB library
// create an object instance
// configure it for a MySQL connection
$db = NewADOConnection("mysql");
// open connection to database
$db->Connect("localhost", "john", "doe", "db278") or die("Unable to
// execute query
$query = "SELECT title, id FROM library";
$result = $db->Execute($query) or die("Error in query: $query. " .
// print HTML menu
print $result->GetMenu("library", '', false);
// close database connection
The GetMenu() method takes a number of arguments, which can
be used to control the behaviour of the generated list box. The first argument is the name for the list ("library", in this case); the second is the default value for the list; the third lets you specify whether the first item in the list should be empty; and the fourth lets you control whether or not the list allows multiple selection.
Here's the HTML code generated by the script above:
As you can see, the contents of the list box are built from
the resultset returned by the query; the first column of the resultset becomes the label for each list item, while the second is the corresponding value.
The GetMenu() method can simplify the task of developing a Web form substantially, significantly reducing the amount of code you have to write - consider using it the next time you need to build a list box from the records in a database.