2011-03-03 184 views
6

有没有简单的方法来获取多个复选框的值并将它们存储在数据库中?获取复选框的所有值?

<?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> 
+1

将'name =“fruit”'改为'name =“fruit []”',移除'$ fruit = $ _POST ...',将'echo $ fruit;'改为'echo implode(',' $ _POST ['fruit'])' – acm 2011-03-03 15:42:49

+0

将复选框命名为“name = fruit []”,以便将它们发送到数组 – Michael 2011-03-03 15:43:39

回答

23

如果您给复选框使用相同的名称,以[]结尾,则值将作为数组返回。

<input type="checkbox" name="fruit[]" value="apple" /> 
<input type="checkbox" name="fruit[]" value="grapefruit" /> 
在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。请原谅明显的错误,这个例子可能会大喊“我有一个苹果”......我没有想到让这个例子足够聪明以确定何时使用“a”,何时使用“an”:P

5

名称您输入这样的:

<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 /> 

然后在$ _ POST迭代[ '果实']:

if(isset($_POST['fruit']) && !empty($_POST['fruit'])) 
    foreach($_POST['fruit'] as $fruit) echo $fruit; 
1

要添加到其他的解决方案......

爆炸和爆炸可以用于PHP将水果数组[]转换为逗号分隔列表。

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

一旦你有你的逗号分隔的列表,良好的数据类型来表示在MySQL中的复选框会SET,并且您可以用逗号分隔列表粘贴到您的插入语句。