PHP复选框,带2个正确答案

时间:2016-10-27 23:03:51

标签: php checkbox

我正在做一个测验,下面是一个html复选框。

<p>3. The J2EE components includes:</p>
            <p><label for="JavaDevelopmentKit">
               <input type="checkbox" id="JavaDevelopmentKit" name="category[]" value="JavaDevelopmentKit"/>Java Development Kit</label></p>
            <p><label for="VisualStudio">
               <input type="checkbox" id="VisualStudio" name="category[]" value="VisualStudio"/>Uses Visual Studio</label></p>
            <p><label for="WriteOnce">
               <input type="checkbox" id="WriteOnce" name="category[]" value="WriteOnce"/>Write Once Run Anywhere technology</label></p>

这是我的PHP代码

 if ($q3 == ""){
            $errMsg = "<p>You must answer question 3.</p>";
        }
        else if (isset($_POST['JavaDevelopmentKit']) && isset($_POST['WriteOnce'])
                $total++;
            }

我的PHP for复选框无效。

即使我将其更改为

 if ($q3 == ""){
                    $errMsg = "<p>You must answer question 3.</p>";
                }
                else if (isset($_POST['JavaDevelopmentKit'])
                        $total++;
                    }

总计不会增加1。

[编辑]

我做了@mahaidery告诉我的,我目前的php是

if ($q3 == ""){
    $errMsg = "<p>You must answer question 3.</p>";
}
else if (isset($_POST['category'])){
    $i = 0;
    foreach($_POST['category'] as $k=>$v){
        if (($key == "JavaDevelopmentKit") || ($key == "WriteOnce") || ($key == "Javadatabase") || ($key == "Opendatabase" ) || ($key == "Security")){
            $i++;
        }
    }
    if($i == 5){
        $total++;
    }
    }

它显示了很多Notice: Undefined variable: key

1 个答案:

答案 0 :(得分:0)

你在PHP中做错了。 这就是你如何做到的。

<?php
if(isset($_POST['category'])){
    //You can also count the total checked by the following line of code
    //$count = count($_POST['category']);
    //or
    //You can loop thru
    $i=0;
    foreach($_POST['category'] as $k=>$v){
        //$k is the number $v hold the value..
        //you can add the counter here like
        $i++;
    }
    if($i <= 2){
        //do your stuff here
    }
}
?>