0

So I am trying to put together a voting system for each entry of a thread. Each entry gets a set of radio buttons (1, 2, 3) and a submit button is at the bottom. I want people voting to make sure they select one of the three radio buttons for each entry. I thought my code was working, but it's not. The last entry if it is selected, and all others aren't, it still says that its fine. But if I don't select the last entry it is working.

<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" />

So then on my vote.php page after hitting submit:

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

It works except for the last entry, if the last entry is selected and others aren't it still thinks all entries have been selected

4

2 回答 2

1
  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">';
    ...

投票.php

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

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

于 2013-05-19T19:42:56.750 回答
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()or print_r()

于 2013-05-19T17:56:01.540 回答