Reputation: 2129
I have created and html form which have a drop down list.
This drop down list is populated from database.
<select name="classes">
<?php
foreach() {
?>
<option value="<?php echo $id ?>"><?php echo $name ?></option>
<?php
}
?>
</select>
Now I want to get the $id and $name both. How will I do this?
I have tried this
echo $_POST['classes'];
But it only displays the $id of the select item. And I want $id and $name both.
Upvotes: 2
Views: 8707
Reputation: 1
<options value="<?php echo $id."_".$name; ?>"><?php echo $name?></option>
Upvotes: 0
Reputation: 4631
You want is and name both so while storing option value , put like this
<option value="<?php echo $id."_".$name;?>"><?php echo $name?></option>
and on posting data just explode the value you will get both is and name
Upvotes: 1
Reputation: 3729
As far as I know, when you submit that form, only the value is going to be carried over. If there is no value then the inner HTML becomes the value.
What I'd do is:
<select name="classes">
<?php
foreach($classes as $id => $name) //i'm guessing here, is this what you meant?
{ ?>
<option value="<?php echo $id.'|'.$name ?>"><?php echo $name ?></option>
<?php } ?>
</select>
In case you are not familiar, the period is the concatenation operator. Think of it as glue for pieces of a string. So I'm gluing $id to the left of "pipe" and then gluing $name onto the end of that. Then in your handler, use split or explode to separate the two values on the pipe.
Actually, I'd do it a little different, echoing more and going in and out of php/html less, but I tried to leave your code intact as much as possible.
Upvotes: 2
Reputation: 25435
You can't. One possibility would be placing both infos inside the value
attribute, and then separating them back again with php (by using a delimiter):
<option value="<?php echo $id.'|'.$name; ?>"><?php echo $name ?></option>
In PHP:
$datas = explode('|',$_POST['classes']);
$id = $datas[0];
$name = $datas[1];
But that's not how the system is meant to be. Usually the $name would be used only as a "friendly" info for the user, cause the value might sometimes just be an INT and user won't understand what that int refers to, so we give him a word description in order to choose an option: but what you would only care of is that value indeed, which you can always use to get again the description that comes along with it (by a search to the database, for ex.)
Upvotes: 6
Reputation: 11
append name to Id and pass it as value,,and explode name from the other end
Upvotes: 1
Reputation: 1490
Sending form means only sending 'value' for select field (treat 'name' in option as a label only). You can simply fetch 'name' from database when you have 'id' while handling form submission.
Upvotes: 0