iheartLUHAN
iheartLUHAN

Reputation: 63

Multiple choice in PHP

How can i save all the inputs(question, choices, answers) in the database? I cant save the correct answer on the database. how can i get the chosen value, which is selected through the radio button? Or is there any other?

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

how will i determine which radio button is selected and how will i get the value of the radio button that is selected?

Upvotes: 0

Views: 4242

Answers (1)

Max Hudson
Max Hudson

Reputation: 10206

You can create a table with questions like so:

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

You can build the page like this:

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

You can check if the answers are correct after the form has been submitted like this:

$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
    }
}

Upvotes: 2

Related Questions