0

I have a page that takes questions from the database and auto generates a survey page. This data is then sent to the same form using POST. The code then breaks down the question into Checkbox/Radio button type, and stores the answer appropriately.

This works perfectly for my radio button type question, but for the checkbox types, only the last selected option is present in the $_POST data.

This is the generated HTML of a sample checkbox question -

1 . Question One 
  <br/>
<fieldset>

        <label for="check[0]">
  <input type="checkbox" class="checkbox" id="check[0]" name="check[0]" value="Opt One" required="required" minlength="2">Opt One 
  </label>

   <br />
      <label for="check[1]"><input type="checkbox" class="checkbox" id="check[1]" name="check[0]" value="Opt Two">Opt Two 
  </label>

   <br />
      <label for="check[2]"><input type="checkbox" class="checkbox" id="check[2]" name="check[0]" value="Opt Three">Opt Three 
  </label>

   <br />
      <label for="check[3]"><input type="checkbox" class="checkbox" id="check[3]" name="check[0]" value="Opt Four">Opt Four 
  </label>

   <br />
    <label for="0" class="error" style="display:none"> Please select at least one option. </label>
  <br/>
</fieldset>

For example if this was the only question and I select "Opt One" and "Opt Two", then print_r($_POST) shows the following -

Array ( [check] => Array ( [0] => Opt Two ) 

Which basically means that Question ID 0's selected option is Opt Two (Opt One has been missed out here).

I can show more code if needed, but as of now I feel this has something to do with my HTML Syntax.

1
  • give different name for check boxs and try... Commented Jan 18, 2014 at 13:14

2 Answers 2

3
<input type="checkbox" name="check[]" value="Opt One" checked>
<input type="checkbox" name="check[]" value="Opt Two" checked>
<input type="checkbox" name="check[]" value="Opt Three" checked>

<?php print_r( $_POST["check"] ); ?>

Output:

Array ( [0] => Opt One, [1] => Opt Two, [2] => Opt Three ) 
Sign up to request clarification or add additional context in comments.

1 Comment

Will this also work if I use name="check0[]" and name="check1[]" ? Update : Ok so it works, but is the way I named it a bad programming practice or is that ok?
0

You can use name=check[] and then see what you get in $_POST

2 Comments

This would work if I had one question only right? Won't it clash if I had a second question?
It will make an array with the options that are selected

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.