Re: question about <select> tag and PHP
| From: | Chris Adams | Date: | Wed, 21 Jun 2000 21:57:17 +0000 |
| Subject: | Re: question about <select> tag and PHP | ||
| References: | 1 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-2541@lists.php.net to get a copy of this message | ||
> A user select a option from the <select> tag of a form (HTML)and store the
> integer value in database. When retrieving the integer value from
database,
> how can I send the value back to <select> tag. ( I can't use preselect
which
> add "selected" in the <option> tag).
You have to put SELECTED in the appropriate OPTION tag when generating the
code. This can be as simple as
<SELECT>
<OPTION VALUE=1 <? if ($ID == 1) echo "SELECTED"; ?>>Text for Option
1</OPTION>
<OPTION VALUE=1 <? if ($ID == 2) echo "SELECTED"; ?>>Text for Option
1</OPTION>
<OPTION VALUE=1 <? if ($ID == 3) echo "SELECTED"; ?>>Text for Option
1</OPTION>
</SELECT>
I prefer to avoid doing that if possible and have a function like the one
below. This works nicely when you have queries that can return two columns
(ID and text), which is extremely common. For example:
function generate_html_select($query, $select_name, $selected_value =
false) {
$html = "";
$html .= "<SELECT NAME=\"$select_name\">\n";
$query_results = mysql_query($query);
$html .= "<OPTION VALUE=\"\">Select...</OPTION>\n";
if (!$query_results) {
error_log("generate_html_select could not load data from
'$query':\nError: " + mysql_errno() . ":\n" . mysql_error());
} else {
while ($query_row = mysql_fetch_row($query_results)) {
$html .= "<OPTION VALUE=\"$query_row[0]\"" . ($query_row[0] ==
$selected_value ? " SELECTED" : "") .
">$query_row[1]</OPTION>\n";
}
}
$html .= "</SELECT>\n";
return $html;
}
echo generate_html_select("SELECT Code, Name FROM Countries ORDER BY Name",
"Country", $Country);