2011-03-03 83 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,並且您可以用逗號分隔列表粘貼到您的插入語句。