如何确保在每个组中至少选择一个单选按钮,php


How to make sure at least one radio button is selected in each group, php

所以我试图为线程的每个条目建立一个投票系统。每个条目都有一组单选按钮(1、2、3(,底部有一个提交按钮。我希望人们投票确保他们为每个条目选择三个单选按钮中的一个。我以为我的代码可以工作,但事实并非如此。最后一个条目,如果它被选中,而所有其他条目都没有,它仍然说它很好。但如果我没有选择最后一个条目,它就起作用了。

<form action="vote.php" method="POST" name="form1"> 
<? $sql = "SELECT * FROM contest_entries WHERE contest_id='$contest_id' ORDER BY id desc";  
$result = mysql_query($sql) or trigger_error("SQL", E_USER_ERROR); 

while ($list = mysql_fetch_assoc($result)) { $username=$list['username']; 
$date=$list['date_entered']; 
$pl_holder=$list['place_holder1']; 
$contest_entry_id=$list['id']; 

echo "1<input name='attending[$contest_entry_id]' type='radio' value='1'>  
2<input name='attending[$contest_entry_id]' type='radio' value='2'> 
3 <input name='attending[$contest_entry_id]' type='radio' value='3'> />";  
}?> 
<input type="submit" name="submit2" id="submit" value="Submit" />

点击提交后,在我的vote.php页面上:

foreach($_POST['contest_entry_id'] as $key => $something) {  
$example = $_POST['attending'][$key]; 

}  if (!isset($example))  { 
    echo "You need to vote for all entries"; 
exit(); 
}else{ 
echo "success!"; 
}  

它除了最后一个条目外都有效,如果选择了最后一个条目的其他条目没有,它仍然认为所有条目都已选择

  1. 您应该在单选选项之前添加具有相同名称的隐藏值,或者再次查询db中的id,以便对所有选项进行正确的迭代
  2. 检查foreach循环内的每个组是否都不同于0/isset((

简单的解决方案:

    ...
    echo '<input type="hidden" name="' . attending[$contest_entry_id] . '" value="0">
    1<input type="radio" name="' . attending[$contest_entry_id] . '" value="1">  
    2<input type="radio" name="' . attending[$contest_entry_id] . '" value="2"> 
    3<input type="radio" name="' . attending[$contest_entry_id] . '" value="3">';
    ...

vote.php

    foreach ($_POST['attending'] as $id => $value) {  
        if ($value == 0) {
            echo 'You need to vote for all entries'; 
            exit; 
        }  
    }  
    echo "success!";  

BTW:如果您希望变量不存在,请不要将值分配给变量(如$example(-直接用isset($_POST[…](检查它们

foreach($_POST['contest_entry_id'] as $key => $something) {  
        $example = $_POST['attending'][$key];

这应该如何工作?您的无线电组的名称为attending[contest-id],所以没有定义$_POST['contenst_entry_id'],是吗?

您的if/else条件应该在foreach-循环括号内。

除此之外,我不能告诉你任何事情——请在迭代var_dump()print_r()之前发布错误或打印global $_POST