Professional Documents
Culture Documents
Here we will look at creating dynamic select lists (note that the technique would work for radio buttons
as well of course) and pre-selecting an element within the list to be the default option.
To help the user complete web forms it is common to provide a select list of options to choose from for
things like category. For example,
<select name="catID">
<option value="2">Bed and Breakfast</option>
<option value="1">Craft Shop</option>
<option value="3">Post Office</option>
<option value="4">Tea Room</option>
</select>
We will look at creating the required html dynamically using php, populating the option tags using data
from, say, a database table. Here the value is usually the primary key (PK) and the word(s) the user sees
and selects is the name/description for that PK.
Lists such as these are typically made from reference or master tables in a database. For example,
category, director, genre, sizes etc.
Example
Here we are querying a table named 'category', using a database connection object named $conn (note
yours may have a different name) and ordering the list by category description.
Example
In this example we are assuming that the catID we already have (the current one) is stored in a variable
called $userRecord->catID and are going to use an IF to assign the value 'selected' to the option tag
if the catID of the option that you're about to display matches the catID you already have.
Page 1 of 2
$sqlCat = "SELECT catID, catDesc from category ORDER BY catDesc";
$rsCat = $conn->query($sqlCat);
echo "<select name='catID'>";
while ($catRecord = $rsCat->fetchObject()) {
if ($userRecord->catID == $catRecord->catID) {
echo "<option value='{$catRecord->catID}' selected>
{$catRecord->catDesc}</option>";
}
else {
echo "<option value='{$catRecord->catID}'>{$catRecord->catDesc}</option>";
}
echo "</select>";
Page 2 of 2