如何检查复选框是否为空


how to check checkboxes whether they are empty or not

如果这是个愚蠢的问题,我深表歉意。我想检查一个或多个复选框是否为空,然后可以处理表单并打印电子邮件的兴趣文本。

HTML/PHP

<p><label for="commentsText">I am interested in:</label><br/>
<input type="checkbox" name="interest[]" id="interest" value="1" class="required requiredField email" /> 
    Exhibiting. Please send me more information<br/>
<input type="checkbox" name="interest[]" id="interest" value="2" class="required requiredField email" /> 
    Visiting. Please add me to your mailing list<br/>
<input type="checkbox" name="interest[]" id="interest" value="3" class="required requiredField email" /> 
    Speaking. Please send me more information<br/>
<input type="checkbox" name="interest[]" id="interest" value="4" class="required requiredField email" /> 
    Attending. Please send me more information<br/>
<?php if($interestError != '') { ?>
<span class="error"><?php echo $interestError; ?></span>
<?php } ?>
</p>

PHP

$interest='';    
if(empty($_POST[$interest]))
{ 
    $interestError ='Please select the interests';
    $hasError = true;
}
else{
    $numberofInterest = count($interest);
    for ($i=0; $i < $numberofInterest; $i++)
    {
        $numofInterest = $interest[i];
        echo $numofInterest . " ";
    }
}

编辑#2

谢谢大家的帮助。我用了print_r,看到四个都打印好了。现在的问题是:如果没有错误,就发送邮件。当我选中所有复选框时,它不会显示所有内容。仅显示"4"。有没有办法显示所有包含的文本?

if(!isset($hasError)) {
        $interest = $numofInterest ;
    $subject = 'I Have A Question to Ask from '.$name;
            $thanksubject = 'Thank you for the Form Submission';
            $body = "Name: $name 'n'nEmail: $email 'n'nInterest: $interest'n'nComments: $comments";

*编辑#3*

好的,我已经解决了上面的最后一个问题。设法发送了包含所有内容的电子邮件。

提交表单时,PHP脚本将分别收到$_GET$_POST变量中的复选框数组(或者您可以只使用$_REQUEST

即,当选中第一个和第三个复选框时,print_r($_POST['interest']);将输出:

Array
(
    [0] => 1
    [1] => 3
)

我认为你的主要错误是对$_POST变量进行索引的方式——你在应该使用字符串'interest'的地方使用了变量$interest,就像上面一样。

让我们打印_r($_POST);发现正在发生的事情。您将了解数据是如何传递的。。以及ti将来如何解决类似的问题。