Reputation: 1
I have inherited a little php page that allows a user to enter relocation requests and then go back in and edit them.
The add page has a number of drop down boxes, but the edit page just shows them as a text field. If you need to select a different value in the edit page you need to know all the values from the drop down box.
I am trying to come up with a way to show the previous selected value from the drop down box in a drop down box on the edit page to easily allow someone to change the value if need be.
I have seen some other questions and answers like this using the 'selected' method but I can't relate that to the code I am looking at. I am not great expert in php and use examples and solutions on here to make things work. In this instance I just cannot put it together.
Appreciate any help.
Thanks
<?php
$resultNames = $conn->query("SELECT txtCraftGroup FROM tblCraftGroup Order
by txtCraftGroup");
if($resultNames) {
?>
<tr>
<td>Craft: </td>
<td><select name="craft">
<option value="0">Please Select</option>
<?php
while ($MCraft = $resultNames->fetch_assoc()) {
echo "<option value=\"{$MCraft['txtCraftGroup']}\">";
echo $MCraft['txtCraftGroup'];
echo "</option>";
}
}else{
?>
<td>Craft: </td>
<td><input type="text" name="craft" value="<?php echo $MCraft; ?>"/><br/>
</td>
<?php
}
?>
</select><td>
</tr>
Upvotes: 0
Views: 1530
Reputation: 11
Working Code:
You can use the selected option. Suppose if you have two forms: Add form. Update form. First post the values in url through the GET method so that you can access the field value in another page.
<select name = "field_name">
<option value="<?php echo $_GET["field_name"]; ?>" selected > <?php echo
$_GET["field_name"]; ?> </option>
{
//you can add your dropdown condition here if you are fetching an array
}
</select>
Upvotes: 1
Reputation: 11
To display the selected option in dropdown
<td><select name="craft">
<?php
while ($MCraft = $resultNames->fetch_assoc())
{ ?>
<option value="<?php echo $MCraft['txtCraftGroup'] ;?>"
<?php if ($MCraft['txtCraftGroup']==$craftval) echo 'selected = "selected"'; ?> >
<?php echo $MCraft['txtCraftGroup']; ?></option>
<?php
}
?>
</select> </td>
For Example
<td><select name="gender">
<?php
while ($row = $resultNames->fetch_assoc())
{ ?>
<option value="male"
<?php if ($row['gender']=="male") echo 'selected = "selected" '; ?> >
Male
</option>
<option value="female"
<?php if ($row['gender']=="female") echo 'selected = "selected" '; ?> >
Female
</option>
<?php
}
?>
</select> </td>
Upvotes: 1