Help with retrieving answers from radio buttons
$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';
mysql_connect($host,$user,$pw);
mysql_select_db($db);
$result = mysql_query("SELECT * FROM Questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
开发者_开发问答 $array[] = $row;
}
for($i=0; $i<=($num_rows-1); $i++)
{
$title = $array[$i]['Title'];
$ans1 = $array[$i]['Answer1'];
$ans2 = $array[$i]['Answer2'];
$ans3 = $array[$i]['Answer3'];
$ans4 = $array[$i]['Answer4'];
echo $title.'<br>';
echo '<form method="post">';
echo '<input type="radio" name="ans'.$i.'">'.$ans1.'<br>';
echo '<input type="radio" name="ans'.$i.'">'.$ans2.'<br>';
echo '<input type="radio" name="ans'.$i.'">'.$ans3.'<br>';
echo '<input type="radio" name="ans'.$i.'">'.$ans4.'<br>';
}
echo '<input type="submit" value="submit" id="submit">';
echo '</form>';
I manage to display the question followed by the corresponding choices and at the bottom a submit button.
How would I, on click of the submit button, get the values that the user have chosen for each question that was looped out from the database? ans1
, ans2
, etc.
This is necessary to compare their answer to the answer key and compute their score.
.help please! Thank you very much and More power!
Assign a value to each of the radio inputs, the updated script could be:
$host = 'localhost';
$user = 'root';
$pw = '';
$db = 'pmdb';
mysql_connect($host,$user,$pw);
mysql_select_db($db);
$result = mysql_query("SELECT * FROM Questions WHERE QuizID=1");
$num_rows = mysql_num_rows($result);
while($row = mysql_fetch_assoc($result))
{
$array[] = $row;
}
//Start the form
echo "<form method=\"post\" action=\"path/to/receiving.php\">\n";
for($i=0; $i<=($num_rows-1); $i++)
{
//Render a question + the answer choices
echo $array[$i]['Title']."<br />\n";
for ($j=1;$j<=4;$j++) {
echo "<input type=\"radio\" name=\"ans$i\" value=\"$j\">".
$array[$i]['Answer'.$j]."<br />\n";
}
}
//End the form
echo "<input type=\"submit\" value=\"submit\" id=\"submit\">\n</form>";
Now to read the values of the answers from within PHP:
echo $_POST["ans1"];
//The answer given for question 1, will be between
// 1-4 or null (if they didn't answer
精彩评论