2013-05-19 41 views
0

所以我试图把一个投票系统对线程的每个条目。每个条目都有一组单选按钮(1,2,3),提交按钮位于底部。我希望投票的人们确保他们为每个条目选择三个单选按钮中的一个。我认为我的代码正在工作,但事实并非如此。最后一个条目如果被选中,而其他所有条目都不是,它仍然会说它很好。但是,如果我不选择它正在工作的最后一个条目。如何确保至少有一个单选按钮每组中选择,PHP

<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
  1. 您应该在无线电选项之前添加具有相同名称的隐藏值,或者再次查询数据库中的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:不分配,如果你希望他们不存在值变量(如$例子) - 直接与isset检查它们($ _ POST [...])

+0

非常感谢,它工作! –

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

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

你的if/else条件应该是foreach -loop括号内。

Appart酒店从我不能告诉你任何东西 - 请张贴错误或做打印global$_POST迭代前,看里面有什么用var_dump()print_r()

+0

没有它的命名参加[contest_entry_id。它必须是一个不同的名称,否则如果我为一个条目选择一个单选按钮,然后尝试为另一个组选择另一个单选按钮,则它只会选择一个,而不允许所有条目都有自己的选择。 –

+0

好,但这是/不是在代码sniplet ...但你的if/else部分应该在foreach循环 –

+0

好吧,现在看起来像这样: foreach($ _ POST ['contest_entry_id'] as $ key => $ something){ $ example = $ _POST ['参加'] [$ key]; 如果(!isset($例子)){ 回声 “你需要把票投给所有条目”; exit(); } else { echo“success!”; } } 靠近!除了现在如果只选择最上面的一个条目它打印出: “成功!您需要为所有条目投票“ 但是,如果我不选择顶部条目并选择其他条目,则它会正确打印: ”您需要为所有条目投票。“ –

相关问题