10

Is there an easy way to get the values of multiple checkboxes and store them in the database?

<?php
if(isset($_POST['go'])){
   $fruit = $_POST['fruit'].",";
   echo $fruit;
   // if you selected apple and grapefruit it would display apple,grapefruit
}
?>
<form method="post">
Select your favorite fruit:<br />
<input type="checkbox" name="fruit" value="apple" id="apple" /><label for="apple">Apple</label><br />
<input type="checkbox" name="fruit" value="pinapple" id="pinapple" /><label for="pinapple">Pinapple</label><br />
<input type="checkbox" name="fruit" value="grapefruit" id="grapefruit" /><label for="grapefruit">Grapefruit</label><br />
<input type="submit" name="go" />
</form>
The Codesee
  • 3,714
  • 5
  • 38
  • 78
Jay Wit
  • 2,987
  • 7
  • 32
  • 34
  • 1
    change `name="fruit"` to `name="fruit[]"`, remove `$fruit = $_POST...`, change `echo $fruit;` to `echo implode(',',$_POST['fruit'])` – acm Mar 03 '11 at 15:42
  • name the checkboxes "name=fruit[]" so they will be sent to an array – Michael Mar 03 '11 at 15:43

3 Answers3

25

If you give the checkboxes the same name, ending in [], the values are returned as an array.

<input type="checkbox" name="fruit[]" value="apple" />
<input type="checkbox" name="fruit[]" value="grapefruit" />

Then in PHP ...

if( isset($_POST['fruit']) && is_array($_POST['fruit']) ) {
    foreach($_POST['fruit'] as $fruit) {
        // eg. "I have a grapefruit!"
        echo "I have a {$fruit}!";
        // -- insert into database call might go here
    }

    // eg. "apple, grapefruit"
    $fruitList = implode(', ', $_POST['fruit']);
    // -- insert into database call (for fruitList) might go here.
}

PS. please forgive the obvious error, that this example will potentially shout "I have a apple" ... I didn't think to make the example smart enough to determine when to use "a", and when to use "an" :P

The Codesee
  • 3,714
  • 5
  • 38
  • 78
Jeff Parker
  • 7,367
  • 1
  • 22
  • 25
5

Name your input like this :

<input type="checkbox" name="fruit[]" value="apple" id="apple" /><label for="apple">Apple</label><br />
<input type="checkbox" name="fruit[]" value="pinapple" id="pinapple" /><label for="pinapple">Pinapple</label><br />

Then iterate on the $_POST['fruit'] :

if(isset($_POST['fruit']) && !empty($_POST['fruit']))   
    foreach($_POST['fruit'] as $fruit) echo $fruit;
grunk
  • 14,718
  • 15
  • 67
  • 108
1

To add on to the other solutions...

implode and explode can be used in PHP to convert your array of fruit[] into a comma seperated list.

$valueToStoreInDB = implode(",",$_POST['fruit']);
$fruitAsAnArrayAgain[] = explode(",",$dbvalue);

Once you have your comma separated list, a good data type to represent the checkboxes in MySQL would be SET, and you can paste your comma seperated list right into your insert statement.

Jessica Brown
  • 8,222
  • 7
  • 46
  • 82