Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get all values from checkboxes? [duplicate]

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>
like image 961
Jay Wit Avatar asked Mar 03 '11 15:03

Jay Wit


3 Answers

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

like image 69
Jeff Parker Avatar answered Nov 16 '22 14:11

Jeff Parker


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;
like image 36
grunk Avatar answered Nov 16 '22 15:11

grunk


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.

like image 29
Jessica Brown Avatar answered Nov 16 '22 14:11

Jessica Brown