Sarah
Sarah

Reputation: 47

While loop and for statement

I am trying to build an online reading test for my students. I currently have two tables in my database : 'student' and 'questions'. In 'student', I have a row for each student which containts it's name, group number and answers to the questions. Questions cols are called question[1], question [2], and so on.

In 'questions', I have 4 cols : ID, 'first', 'chapter' and 'question'. 'first' is a true/false field, if it is the first question to a chapter its value is 1. I call those with a while loop.

echo '<ol>';
$query = mysql_query("SELECT * FROM `question`");
while($row_q = mysql_fetch_assoc($query)) {
if($row_q['first']==1){
echo '<h2>Chapter '.$row_q['chapter'].'</h2><br>';
}
echo '<li>';
echo $row_q['question'];
echo '</li>';
echo '<br>';
}
echo '</ol>';

It echoes beautifuly. Now, I'm trying to put an input field under each question so the student can give an answer and submit it at the end of the page. How can I do this? I tried using a for($i=1;$i<=10;$i++) statement since I want each field to be named with a different number, but no matter where I insert it, I either end up with a bunch of identical fields next to each other or my questions echoed over and over again.

I'm open to all suggestions. Thanks!

Upvotes: 1

Views: 158

Answers (2)

jspcal
jspcal

Reputation: 51914

echo '<input name="answer[' . htmlspecialchars($row_q['ID']) . ']" type="text" value="" />';

under the question text... Then in PHP var_dump($_REQUEST) to see the answers...

EDIT:

For displaying the saved answer, you'll want to do something like this:

echo '<input name="answer_' . $idx . '" type="text" ' .
  value="' . htmlspecialchars($student_row["answer_$idx"]) . '" />';

and maintain a counter $idx as you loop...

That's if your answer are laid out flat in the student table per your description and the answer value columns are named "answer_1" etc.

If the answers are normalized in a separate table, you can join the tables together:

select * from question q left join answer a on a.question_id = q.question_id and
  a.student_id = <current student id>

Upvotes: 0

mynewaccount
mynewaccount

Reputation: 446

there's no need to do a for loop, you're already in a loop :) just set a variable called question number and increment it in the while loop.

$question_number =1;

echo '<ol>';
$query = mysql_query("SELECT * FROM `question`");
while($row_q = mysql_fetch_assoc($query)) {
    if($row_q['first']==1){
        echo '<h2>Chapter '.$row_q['chapter'].'</h2><br>';
    }
    echo '<li>';
    echo "<label>$question_number".$row_q['question']."</label>";
    echo "<input type='text' name='$row_q[\'ID\']'></input>";
    echo '</li>';
    echo '<br>';

    $question_number++; 
}
echo '</ol>';

Upvotes: 1

Related Questions