So ya want to populate a select field?
In this case, a combobox (size=1).
Just a matter of sucking up all rows in
the query:
[ex.1]
$Query = "SELECT ID,FieldName FROM TableName";
$Results = mysql_query($Query,$DBLink);
if (mysql_num_rows($Results)) {
print '<SELECT NAME="MultiSel" SIZE=1>';
print "\n";
while ($row = mysql_fetch_object($Results)) {
print "<OPTION>$row->FieldName\n";
}
print "</SELECT>\n";
} else {
print "<FONT COLOR=RED>No Values!</FONT>\n";
}
If you want to have multiple selections, try changing the first print statement, add the MULTIPLE parameter and brackets to the SELECT field:
[ex.2]
print "<SELECT NAME=\"MultiSel[]\" MULTIPLE SIZE=5\n";
On the next page, you'll be able to access
the selections via an array, MultiSel:
[ex.3]
// Print out selections from form submission
for ($i = count($MultiSel)-1; $i >= 0; $i--)
{
print "$MultiSel[$i] <br>\n";
}
There are a few methods of restoring the
original select box. The first one (and easiest) is to add all the selections to
the top of the new SELECT box, then write a query to exclude those selections:
[ex.4]
// Add previous submissions to the SELECT box
// and generate exclusive query.
print "<SELECT NAME=\"MultiSel\" MULTIPLE SIZE=5\n";
$Query = "SELECT * FROM TableName";
if (count($MultiSel)) {
$Query .= "WHERE ";
for ($i = count($MultiSel)-1; $i >= 0; $i--)
{
print "<OPTION SELECTED>$MultiSel[$i]\n";
$Query .= "(FieldName != '$MultiSel[$i]') AND ";
}
// Remove trailing AND
$Query = substr($Query,0,-4);
}
while ($row = mysql_fetch_object($Results)) {
print "<OPTION>$row->FieldName\n";
}
print "</SELECT>\n";
That's the basics of it. Of course there
are a few optimizations, like checking on
the last routines to see if there are any DB
results or submissions at all. These are
simple to add so I'll leave them to anyone
else.
Hope it helps!