I'm making online test/quiz for students and using PHP and MySQL. Currently I have a form, where I can add the questions and answers into the database.
However, I have trouble with submitting correct answers into the database by selecting multiple checkboxes. I want to store all correct answers in the table called correct_answer(id, question_id, answer_id) and insert all selected id's from the table called answers(id,answer_id, answer).
How can I insert only selected checkboxes values and skip somehow unchecked checkboxes?
My HTML part:
<form id="add_question_form" method="post">
<label>Question: *</label>
<input id="question" type="text" name="question" class="form_default" placeholder="Type your question here" required>
<div class="inputs">
<label>Answer #1: *</label>
<input type="text" id="answer" name="dynamic[]" class="form_default" placeholder="answer" required/>
<input type="checkbox" name="selected_item[]" id="checkbox" value="<?php echo $answer_id;?>">
<label>correct</label>
<br>
<label>Answer #2: *</label>
<input type="text" id="answer" name="dynamic[]" class="form_default" placeholder="answer" required/>
<input type="checkbox" name="selected_item[]" id="checkbox" value="<?php echo $answer_id;?>" />
<label>correct</label>
<br>
</div>
<input id="submit" type="submit" name="add_question" value="Submit" class="button">
</form>
PHP code:
if (isset($_POST['add_question'])) { // Checks if the form has been submitted
if (isset($_POST['selected_item']) && !empty($_POST['selected_item'])) {
$counter++; // each time adds 1 after user posts the question
$optionArray = $_POST['dynamic']; // submits multiple answers to the database
for ($j = 0; $j < count($optionArray); $j++) {
$answer = mysql_real_escape_string($_POST['dynamic'][$j]); // returns multiple answers
$check_answer = "SELECT id, answer FROM answers WHERE answer = '$answer'";
$check_answer = mysql_query($check_answer); //checks if answer is exist in the database
while ($row = mysql_fetch_assoc($check_answer)) { // fetch a result rows as an associative array
$answer_id = $row['id']; // answer id from database
}
if (mysql_num_rows($check_answer) > 0) {
$q = "INSERT INTO correct_answer (question_id, answer_id) VALUES ('$counter','$answer_id')";
$q = mysql_query($q);
}
}
}
}
For instance:
I'm adding question and three answers "a","b" and "c". Selecting "a" and "c" as correct answer.
All answers have been successfully added to MySQL "answers" table:
1 - a
2 - b
3 - c
- But, instead of adding id ="1" and "3" into "correct_answer" table (as "a" and "c" have these ids numbers), it adds ids of first two answers "1" and "2".. Therefore, it wrongly matching the correct answer and setting up "a" and "b" as correct answer.
Can anyone help me please? I want to insert multiple correct answers, but only if they are selected..
Thanks in advance, any help will be appreciated!