我有一个文本文件,其中包含我用来创建测验的信息。我只是一次只显示一个测验问题。我根据问题的数量生成单选按钮,然后在生成单选按钮的循环之后我有一个提交按钮。当我点击提交时,我无法弄清楚如何获取用户在$ _POST数组中选择的单选按钮。我最初的想法是使用表单标签,然后循环运行,但我不知道这是否有效或如何使其在语法上工作。
textfile(最后一个数字是正确答案的索引):
What does charmander evolve to?#Charmeleon:charizard:squirtle#0
WHo is the main character in Pokemon?#Misty:Ash:Obama#1
脚本:
<?php
$indexTemp = intVal($_SESSION["index"]);
if($_SESSION["numQuestions"] == $indexTemp){
echo "Your Results are: ";
echo "<form action=\"process.php\" method=\"post\"> Back to Main screen: <input type=\"submit\"><br \> </form>";
exit();
}
$filename = $_SESSION["quizOfTheDay"];
$quizStuff = file($filename);
$ctr =1;
$questionInfo = $quizStuff[$indexTemp];
$questionParse = explode("#", $questionInfo);
$_SESSION["correctAns"] = $questionParse[2];
echo $_SESSION["correctAns"]." from line 55 <br />";
$answerChoices = explode(":",$questionParse[1]);
echo "$questionParse[0] ? <br />";
#This is where the radio buttons are being generated
foreach ($answerChoices as $answerChoice) {
echo "<input type='radio' name='ans$ctr' id='q1' value='$ctr'> <label for='q1'> $answerChoice </label> <br />";
$ctr +=1;
}
$_SESSION["index"] = $indexTemp +1;
echo "<form action=\"questions.php\" method=\"post\"> <input type=\"submit\"><br \> </form>";
?>
答案 0 :(得分:0)
从单选按钮和复选框中获取数据可能有点棘手,通常是由于对单选按钮和复选框的工作原理缺乏了解。
记住两个事实很重要:
更新foreach,因为所有单选按钮必须same name
,但值不同。
<?php
foreach ($answerChoices as $answerChoice) {
echo "<input type='radio' name='ans' id='q1' value=".$ctr."> <label for='q1'>".$answerChoice."</label> <br />";
$ctr +=1;
}
?>
现在你的for-each连接也看起来不对,我已经更新了,因为连接错误,所以这个值不会显示在单选按钮中。单选按钮值将是增量变量的计数。
答案 1 :(得分:0)
删除$ ctr
foreach ($answerChoices as $answerChoice) {
echo "<input type='radio' name='ans' id='q1' value='$ctr'> <label for='q1'> $answerChoice </label> <br />";
$ctr +=1;
}