且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取复选框的所有值?

更新时间:2023-10-08 08:20:28

如果您给复选框使用相同的名称,

 < input type =checkboxname =fruit [] value =apple/> 
< input type =checkboxname =fruit []value =grapefruit/>

然后在PHP中...



foreach($ _ POST ['fruit'])$ p> 作为$ fruit){
// eg。 我有一个葡萄柚!
回声我有一个{$ fruit}!;
// - 插入数据库调用可能会在这里
}

// eg。 apple,grapefruit
$ fruitList = implode(',',$ _POST ['fruit']);
// - 插入数据库调用(for fruitList)可能会在这里。
}

PS。请原谅明显的错误,这个例子可能会大喊我有一个苹果......我没有想到让这个例子足够聪明以确定何时使用a,何时使用an:P

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>

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