You are on page 1of 2

Creating dynamic select lists and pre-selecting an element

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.

Building dynamic select lists for forms

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.

To steps to create such a list dynamically are normally


 Create an appropriate SQL statement
 Retrieve the record set
 Display an opening select tag
 Iterate over (i.e. loop through) the record set getting each record in turn
 Create an option for each record
 Display the closing select tag

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.

$sqlCat = "SELECT catID, catDesc from category ORDER BY catDesc";


$rsCat = $conn->query($sqlCat);
echo "<select name='catID'>";
while ($catRecord = $rsCat->fetchObject()) {
    echo "<option value='{$catRecord->catID}'>{$catRecord->catDesc}</option>";
}
echo "</select>";

Pre-selecting an element within a list to be the default option


We often want to pre-select option in a web form’s select list as the default value. For example, in the
case of an update type web form when we want to set the option that matches the current id as the
default. One way to do this is to use an IF statement to check if the id you're about to display matches
the id you already have.

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

You might also like