0

Possible Duplicate:
Get $_POST from multiple checkboxes

I'm a little new to web development and this is a problem (having completely stumped me) I feel has a simple solution, so I won't beat around the bush trying to figure it out myself. I will also focus on the most important bits.

I have some PHP code that is outputting a table, a form and a checkbox next to each row. Each one of the checkboxes looks like this:

<input type="checkbox" name="data_id" value="1">
<input type="checkbox" name="data_id" value="2">
<input type="checkbox" name="data_id" value="3">

As well as the submit button:

<input type='submit' name='Submit' value='Submit'/>

Standard form setup, nothing special.

I'd like to get the checked items in an array, however when I retrieve the data from the form using $_POST:

if($_POST['data_id'])
    {
        var_dump($_POST['data_id']); //returns string
        print_r($_POST['data_id']); //shows only one checkbox value
    };

What exactly am I doing wrong that the variable is not being returned an array?

Community
  • 1
  • 1
styke
  • 2,116
  • 2
  • 23
  • 51

3 Answers3

1

PHP's form-to-array syntax requires [] in the element name:

<input type="checkbox" name="data_id[]" value="1">
                                    ^^
Marc B
  • 356,200
  • 43
  • 426
  • 500
1

When PHP parses data to $_POST/GET/REQUEST it only presents the data as an array if the field name ends in [] or [some_index] (otherwise it drops all but one of the values).

Rename the fields:

<input type="checkbox" name="data_id[]" value="1">
<input type="checkbox" name="data_id[]" value="2">
<input type="checkbox" name="data_id[]" value="3">

… or get the raw post data and parase it yourself. (I don't recommend this latter approach).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
0

Try

<input type="checkbox" name="data_id[]" value="1">
<input type="checkbox" name="data_id[]" value="2">
<input type="checkbox" name="data_id[]" value="3">
Mohit Mehta
  • 1,283
  • 12
  • 21