I'm having trouble understanding the logic behind a survey style script i'm working on.
I've written the first part where I pull the question and answer from the db but I can't figure out how I can create a multiple choice for each question whilst in the while loop and then store the value the user has selected. My brain is fried trying to figure it out :(
first part of my code is straight forward I think:
<?php
//retreive questions from database and put into question box
$query = "SELECT `Question`, `Answer` FROM `questions`";
$question = mysql_query($query);
while($row = mysql_fetch_assoc($question)){
?>
<div id="ContainerQuestion">
<span style="Question">Question <?php echo $row['Question']; ?></span>
// Have A,B,C,D outputted as values in a checkbox and then the text after????
</div>
<?php
}
?>
I'd really appreciate any help.
Do you mean this?
while($row = mysql_fetch_assoc($question)){
?>
<div name="ContainerQuestion">
<span style="Question">Question <?php echo $row['Question']; ?></span><br />
<input type="checkbox" name="question_<?= $row['Question_ID']; ?>[]" value="A" <?= $row['Answer'] == 'A' ? 'checked="checked"' : '' ?> /> A<br />
<input type="checkbox" name="question_<?= $row['Question_ID']; ?>[]" value="B" <?= $row['Answer'] == 'B' ? 'checked="checked"' : '' ?>/> B<br />
<input type="checkbox" name="question_<?= $row['Question_ID']; ?>[]" value="C" <?= $row['Answer'] == 'C' ? 'checked="checked"' : '' ?>/> C<br />
<input type="checkbox" name="question_<?= $row['Question_ID']; ?>[]" value="D" <?= $row['Answer'] == 'D' ? 'checked="checked"' : '' ?>/> D<br />
// Have A,B,C,D outputted as values in a checkbox and then the text after????
</div>
<?php
}
NOTE: You shouldn't give the <div>
a static (read: non-unique) ID within the loop - HTML rules state that IDs must be unique.
Also, if the user may only select one option, you may want to use radio buttons instead.
$opts = array(
'a' => 'foo',
'b' => 'bar',
'c' => 'baz',
'd' => 'all of the above'
);
foreach($opts as $key => $val) {
echo <<<EOL
<input type="checkbox" name="something" value="{$key}" /> {$val}<br />
EOL:
}