views:

67

answers:

1

Hi, I'm new to PHP, and I can't figure this out.

I'm trying to figure out how to access the data of a group of select boxes I have defined in my HTML code. I tried grouping them as a class, but that doesn't seem to work... maybe I was doing it wrong.

This is the following HTML code.

<form action="" method="post">
<select class="foo">
 <option> 1.....100</option>
</select>
<select class="foo">
 <option> 1.... 500></option>
</select>
<input type="submit" value="Submit" name="submit"/>
</form>

I essentially want to group all my select boxes and access all the values in my PHP code.

Thanks

+1  A: 

Use the name attribute in your select tags. Then you can access those fields by name in the $_POST variable.

<form action="" method="post">
<select name="number_one">
   <option value='1'>1</option>
   <option value='2'>2</option>
   <option value='3'>3</option>
</select>
<select name="number_two">
   <option value='a'>1</option>
   <option value='b'>2</option>
   <option value='c'>3</option>
</select>
<input type="text" name="something"/>
<input type="hidden" name="hidden_value" value="hidden"/>
<input type="submit" value="Submit" name="submit"/>
</form>

In your PHP you can access these like so:

$number_one = $_POST['number_one'];
$number_two = $_POST['number_two'];
$something = $_POST['something'];
$hidden_value = $_POST['hidden_value'];
thetaiko
ah thanks that worked
2Real
what if i'm building up a dynamic list? my list of select boxes can change depending on how many a user chooses to have on screen
2Real
Any form element that contains a `name` attribute can be accessed in $_POST (assuming you use 'post' as your method). If you have two elements with the same name, the second will overwrite the first. You can introduce arrays by adding brackets. I.e. `<select name='something[one]'>...` and `<select name='something[else]'>...`. It sounds as though that's the direction your heading.
thetaiko
Oh, arrays can be accessed in `$_POST` like `$_POST['something']['one']` and `$_POST['something']['else']`
thetaiko
ah ok thanks this is what i was looking for
2Real