I have the following code that generates a dropdown list. I want the value selected to be the default value of the same drop-down list on another page. The code I am using to generate the drop-down list is area_index.php
:
// Write out our query.
$query = "SELECT * FROM hub";
// Execute it, or return the error message if there's a problem.
$result = mysql_query($query) or die(mysql_error());
$dropdown = "<select name='hub'>";
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "
<option value='{$row['name']}'>{$row['name']}</option>";
}
$dropdown .= "
</select>";
?>
<form method="post" align= "right">
<table >
<tr>
<td>Select the Hub for which you want to add and area: </td>
<td><?php echo $dropdown; ?></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="submit" value="Add" align= "right" /></td>
</tr>
</table>
I want to display the same drop-down list in my page called area_view.php
but the default value of the drop-down list must be equal to the selected value.
The variable in area_index.php
used is $hub_name = $_POST['hub'];
Change your while loop to this:
while($row = mysql_fetch_assoc($result)) {
$dropdown .= "
<option value='{$row['name']}'" . ($row['name'] == $_POST['hub'] ? "selected" : "") . ">{$row['name']}</option>";
}
This checks to see if the value you're passing as $_POST['hub'] from the previous page equals the value of $row['name'] for each option being added. For the one that's equal, it will add the attribute selected
, which will cause the browser to show that option as the selected one.