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

时间:2013-05-19 17:39:11

标签: php radio-button

所以我试图为一个线程的每个条目组合一个投票系统。每个条目都有一组单选按钮(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!"; 
}  

除最后一个条目外,如果最后一个条目被选中而其他条目不被选中,它仍然认为所有条目都已被选中

2 个答案:

答案 0 :(得分:1)

  1. 你应该在无线电选项之前添加具有相同名称的隐藏值,或者再次为id再次查询数据库,以便通过所有选项进行适当的迭代。
  2. 检查foreach循环中每个组是否与0 / isset()不同。
  3. 简单的解决方案:

        ...
        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!";  
    

    顺便说一句:如果您希望它们不存在,请不要为变量赋值(如$ example) - 直接使用isset($ _ POST [...])

    检查它们

答案 1 :(得分:0)

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

这应该如何运作?您的广播组的名称为attending[contest-id] - 因此$_POST['contenst_entry_id']未定义 - 是吗?

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

从那里我无法告诉你任何事情 - 请发布错误或打印global $_POST,然后再进行迭代,以查看var_dump()print_r()内部的内容。< / p>

相关问题