I have this array that populates a dropdown menu. The key is my database key and the value is the corresponding database value. The issue I am having is that when I POST the form, I am getting the POSTed numerical value instead of the string value in the dropdown list. I could query the database to get the string but there has to be a better way of doing this as I already have both values in an array. I can't use array_search because the the array is multidimensional. Can someone please offer a hand?
Thanks
foreach($dd as $k=>$v)
{
echo'<option value="'.$v['ace_id'].'">'.$v['arua'].'</option>';
}
The HTML input
fields (this also includes select
, textarea
and button
) only sends the name-value pairs to the server side (as been specified in the name
and value
attribues). They does not send any textual representation along it.
You already know the text and the labels in the server side beforehand (how else would you have printed them?), there's absolutely no point of having them in the request parameters.
You can solve this "problem" in several ways:
value
attribute, not as option label.Update: here's a basic example (without sanitity checks like isset
and htmlspecialchars
, but that's up to you):
$selected = $_POST['dropdownname'];
foreach ($options as $value => $label) {
echo '<option value="' . $value . '"' . ($value == $selected ? ' selected' : '') . '>' . $label . '</option>';
}
If you want the text name in the dropdown instead of the key, then put that in the value="" part. If you want both, then put both in there and seperate them with a comma and run split() on it.