PHP Application Development With ADODB (part 2) - What's On The Menu? (
Page 5 of 7 )
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:
<html>
<head></head>
<body>
<?php
// include the ADODB library
include("adodb.inc.php");
// 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
connect!");
// execute query
$query = "SELECT title, id FROM library";
$result = $db->Execute($query) or die("Error in query: $query. " .
$db->ErrorMsg());
// print HTML menu
print $result->GetMenu("library", '', false);
// close database connection
$db->Close();
?>
</body>
</html>
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:
<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, 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.