I have to build a quiz and I am struggling to get two arrays into my insert, I have tried to combine my arrays but that still doesn't work.
I have a hidden field that sends through the question_id, which is an array cause. I have to send trough all the question id's.
<input type="hidden" name="question_id[]" value="<?=$row_ass['uid']?>" />
Then I have check boxes that have to be unique cause, there are alot of questions on one page.
$countquestion++;
?>
<ol>
<li type="a">
<input type="radio" name="answer[<?=$countquestion?>]" value="answer1" /> <?=$row_ass['answer1']?>
</li>
My problem is in getting the values of both values of the array into the INSERT, at the moment everything INSERTS correctly except for the question_id it only adds the last question_id and makes the other one 0.
Submit page:
$sql_data = array();
$sql_prefix = "INSERT INTO student_score(course_uid, student_uid, question_uid, answer) VALUES";
foreach($_POST['answer'] as $id => $answer){
$course_id = (int) $_POST['course_id'];
$student_id = (int) $_POST['student_id'];
$question_id = (int) $_POST['question_id'][$id];
$answer = mysql_real_escape_string($answer);
$sql_data[] = "($course_id, $student_id, $question_id, '$answer')";
}
$sql = $sql_prefix.implode(",
", $sql_data);
if(!mysql_db_query($dbName, $sql, $connect)){
$_SESSION['msg'] = "Could not save information, Please try again";
header("Location:student_assignment.php");
}
else{
$_SESSION['msg'] = "Question successfully created";
header("Location:student_assignment.php");
}
If someone can please help me, I would appreciate it.
Your question_id
doesn't have any indexes.
Look at your answer
. You put name="answer[<?=$countquestion?>]"
. The answers have the index of the question number. Sicne you're trying to get the question to the answer, you need to add the index to the question fields:
name="question_id[<?=$countquestion?>]"
or perhaps
name="question_id[<?=$row_ass['uid']?>]"
Not really sure which one you should use, but you should know.
ALSO, try not to use the short tags <?= ?>
. It may look cleaner, but it's very bad practice and causes a lot of headaches (escpecially since they will be gone in future PHP versions)
EDIT: It's also helpful when debugging troubling code to add things like print_r($_POST)
to see exactly what's being sent when the form is submitted. =)