koala421
koala421

Reputation: 816

How can I populate an HTML <select> element with values from a database?

I am trying to get values from a database and place them in a dropdown list within an HTML <select> tag.

I'm able to get the values in a long string and display all of them within a single option but I want to put each value in a separate <option> tag. I just don't know what logic I could use to do this.

Here's what I have so far:

#!c:\perl\bin\perl.exe

use CGI;
require ("data_eXchangeSubs.pm");

$query = new CGI;
print $query->header(-expires=>'-1d');

print $query->start_html(
    -title=>'Dex Vendor Testing',
    -bgcolor=>'white'
);

$user = $query->param("user");

my $dataX = ${ConnectToDatabase($main::DBone, $main::dataENV)};

$resultSet = $dataX->Execute("select vendor from dex_vendor_info group by vendor");
while(!$resultSet->EOF) {
    $vendors .= $resultSet->Fields("vendor")->Value."\n";
    $resultSet->MoveNext;
}
print <<ONE;
    <table width=75% border=0>
    <th colspan=2 align=left><strong><font size=5pt color=#FF6633 face=garamond>Vendor Information</strong</font><hr size=4pt color=midnightblue></th>

    <tr>
    <td align=left nowrap><font size=4pt face=garamond><label id=lVendor for=vendor><strong>Company Name</strong></font></label></td>
    <td align=left nowrap><font size=4pt face=garamond><label id=lVendor for=vendor><strong>Contact's Name</strong></font></label></td>
    </tr>

    <tr>
    <td align=left nowrap><select id="vendors">
        <option>$vendors</option>

        </td>
    </td>
    <td align=left nowrap><input type=text name="contact" id=contact value="" size=25></td>
    </tr>

    </table>
    <br>
ONE

print $vendors;
print $query->end_html;

Upvotes: 0

Views: 706

Answers (1)

Axeman
Axeman

Reputation: 29854

If you're using CGI, then use CGI.

print $query->popup_menu( 
      -name    => 'vendors'
    , -values  => \@list_of_vendors
    , -default => $default_vendor
    );

And you get @list_of_vendors in your row processing loop:

my @list_of_vendors;
while(!$resultSet->EOF) {
    push @list_of_vendors, $resultSet->Fields("vendor")->Value;
    $resultSet->MoveNext;
}

If you want labels to be a different text value from values include -labels tag in the call and point it to an array ref containing the text you want visible.

Upvotes: 1

Related Questions