PHP中的多项选择

时间:2012-07-09 15:19:54

标签: php

如何在数据库中保存所有输入(问题,选择,答案)? 我无法在数据库中保存正确的答案。我怎样才能获得通过单选按钮选择的所选值?或者还有其他吗?

<form action="test2.php" method="post">
<?php
if($numMC > 0)
    {

echo "<b>"."MULTIPLE CHOICE QUESTIONS: Enter them below followed by their correct answer."."</b>";
        echo "<br>"; 

        for ($j=1; $j<=$numMC; $j++)
            {?> 
<p><textarea name="question[<?php echo $j; ?>]" rows=3 cols=90>question[<?php echo $j; ?>]</textarea></p>
            <?php for($k=1;$k<=$numchoices;$k++)
                {
                echo $k; ?>
                <input type="radio" name="right[<?php echo $j; ?>]">
                <input type="text" name="choice[<?php echo $j; ?>][<?php echo $k; ?>]" value="choice[<?php echo $j; ?>][<?php echo $k; ?>]"><br />
<?php               }

                echo "<br>"."<br>";
            }

    } ?>

<input type="submit">     

我将如何确定选择哪个单选按钮以及如何获取所选单选按钮的值?

1 个答案:

答案 0 :(得分:2)

您可以创建一个包含以下问题的表格:

----------------------------------------------------
| questionId | answer                    | correct |
----------------------------------------------------
| 1          | Possible answer 1a        | 0       |
----------------------------------------------------
| 1          | Possible answer 1b        | 1       |
----------------------------------------------------
| 2          | Possible answer 2a        | 1       |
----------------------------------------------------
| 2          | Possible answer 2b        | 0       |
----------------------------------------------------

您可以像这样构建页面:

$sql = mysql_query("SELECT * FROM questionsTable");
while($row = mysql_fetch_assoc($sql)){
echo '<input type="radio" value="'.$row['answer'].'" name="q'.$row['id'].'"/>
}

您可以在提交表单后检查答案是否正确:

$sql = mysql_query("SELECT * FROM questions");
while($row = mysql_fetch_assoc($sql)){
    $radioName = 'q'.$row['id'];
    if($row['correct'] == 1){
        //handle a correct answer here
    }
}