PHP复选框表单检索,尝试了所有stackoverflow解决方案

时间:2014-03-27 23:18:22

标签: php html checkbox

<table>
                            <col width="250">
                            <col width="250">
                            <col width="250">
                            <tr><td>
                                    <input type="checkbox" name="toppings[]"/>Pepperoni<br>
                                    <input type="checkbox" name="toppings[]"/>Mushroom<br>
                                    <input type="checkbox" name="toppings[]"/>Bacon
                                </td>

                                <td>
                                    <input type="checkbox" name="toppings[]"/>Onion<br>
                                    <input type="checkbox" name="toppings[]"/>Tomatoes<br>
                                    <input type="checkbox" name="toppings[]"/>Olives
                                </td>

                                <td>
                                    <input type="checkbox" name="toppings[]"/>Pineapple<br>
                                    <input type="checkbox" name="toppings[]"/>Green Pepper<br>
                                    <input type="checkbox" name="toppings[]"/>Extra Cheese
                                </td>
                            </tr>
                        </table>

$toppings = isset($_POST["toppings[]"]) ? $_POST["toppings[]"] : array("");
foreach($toppings as $chk => $selection){
    echo $selection . ", ";
}

/ *
    出于何种原因,我的$选择值始终为空。我打印过的最多的是&#34; on&#34;只有在至少有一个复选框被勾选时才会打开。我尝试了30多种不同的解决方案来迭代复选框数组,但似乎没有任何效果。我做错了什么?

Sorry for the poorly formatted code, and thanks in advance for the help.

* /

1 个答案:

答案 0 :(得分:1)

尝试将value=属性添加到您的复选框

<tr><td>
    <input type="checkbox" name="toppings[]" value="Pepperoni" />Pepperoni<br>
    <input type="checkbox" name="toppings[]" value="Mushroom"/>Mushroom<br>
    <input type="checkbox" name="toppings[]" value="Bacon" />Bacon
</td>

<td>
    <input type="checkbox" name="toppings[]" value="Onion" />Onion<br>
    <input type="checkbox" name="toppings[]" value="Tomatoes" />Tomatoes<br>
    <input type="checkbox" name="toppings[]" value="Olives" />Olives
</td>

<td>
    <input type="checkbox" name="toppings[]" value="Pinapple" />Pineapple<br>
    <input type="checkbox" name="toppings[]" value="Green Pepper" />Green Pepper<br>
    <input type="checkbox" name="toppings[]" value="Extra Cheese" />Extra Cheese
</td></tr>

并检查$_POST["toppings"],而不是$_POST["toppings[]"]

$toppings = isset($_POST["toppings"]) ? $_POST["toppings"] : array();
if(!empty($toppings)){
   foreach($toppings as $chk => $selection){
        echo $selection . ", ";
   }