Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to handle multiple checkboxes in a PHP form?

Tags:

html

php

I have multiple checkboxes on my form:

<input type="checkbox" name="animal" value="Cat" />
<input type="checkbox" name="animal" value="Dog" />
<input type="checkbox" name="animal" value="Bear" />

If I check all three and hit submit, with the following code in the PHP script:

if(isset($_POST['submit']) {
   echo $_POST['animal'];
}

I get "Bear", i.e. the last chosen checkbox value even though I picked all three. How to get all 3?

like image 755
Jake Avatar asked Jul 30 '11 04:07

Jake


People also ask

How do I insert multiple checkboxes?

To insert more than one checkbox, go to the Developer Tab –> Controls –> Insert –> Form Controls –> Check Box. Now when you click anywhere in the worksheet, it will insert a new checkbox. You can repeat the same process to insert multiple checkboxes in Excel.

How can I get checkbox data in PHP?

In order to get the checkbox values, you can use the foreach() method. Note: The foreach() method functions by looping through all checked checkboxes and displaying their values.


2 Answers

<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />

If I check all three and hit submit, with the following code in the PHP script:

if(isset($_POST['animal'])){
    foreach($_POST['animal'] as $animal){
        echo $animal;
    }
}
like image 64
Andrew Winter Avatar answered Sep 28 '22 18:09

Andrew Winter


See the changes I have made in the name:

<input type="checkbox" name="animal[]" value="Cat" />
<input type="checkbox" name="animal[]" value="Dog" />
<input type="checkbox" name="animal[]" value="Bear" />

you have to set it up as array.

print_r($_POST['animal']);
like image 35
fatnjazzy Avatar answered Sep 28 '22 20:09

fatnjazzy