I need to display a dropdown list of hospitals several times (10) in one form and I'm not sure of the best way to go about this. I can get the first list to display, but the subsequent lists just show "Select". This is my code:

<td width=\"200\"><select name=\"hospital1\">
			<option value=\"\"> -- Select -- </option>";
			while ($row = mysql_fetch_array($sqlhosp_result)) {
					$HospInsCo = $row["HospInsCo"];
					echo "<option value=\"$HospInsCo\">$HospInsCo</option>";
			}
			echo "
			</select></td>

I've tried duplicating this code but changing the select name to hospital2, etc. but, again, only get the "Select" option. I'd really like to be able to display the full list of hospitals for the first option and if the user selects a hospital, have that hospital deleted from subsequent lists and so on, but just displaying all the hospitals for all fields would work too.

Member Avatar for langsor

Okay, a couple things to think about ...

First, your multiline html text might be better created using PHP's heredoc format

print <<<ENDLINE
<td width="200">
  <select name="hospital1">
    <option value=""> -- Select -- </option>
ENDLINE;

while ( $row = mysql_fetch_object( $sqlhosp_result ) ) {
print <<<ENDLINE
    <option value="$row->HospInsCo">$row->HospInsCo</option>
ENDLINE;
}

You can use anything, not just ENDLINE/ENDLINE; and of course you can use echo if you prefer, but I like print coming from a perl background.

Second, you are grabbing all of your values in a while loop, so if you need to use those values more than once, you should put them into an array and then reuse the array ...

while ( $row = mysql_fetch_object( $sqlhosp_result ) ) {
  $rows[] = $row->HospInsCo;
}

print <<<ENDLINE
<td width="200">
  <select name="hospital1">
    <option value="">
ENDLINE;

foreach ( $rows as $row ) {
print <<<ENDLINE
    <option value="$row">$row</option>
ENDLINE;
}

Finally, if you want to change the select-options based on what a user selects from the first select box, you will either need to re-submit/reload the page, or use javascript to do the dirty work. Since PHP only works on the server and is done after the page has loaded.

Hope this makes sense and helps

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.