问题的PHP复选框


PHP checkboxes for questions

我很难理解我正在编写的调查风格脚本背后的逻辑。

我已经写了第一部分,从数据库中提取问题和答案,但我不知道如何在while循环中为每个问题创建一个多选项,然后存储用户选择的值。我想弄清楚:(

我的代码的第一部分是直接的,我认为:

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

我真的很感激任何帮助。

你是这个意思吗?

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
}

注意:您不应该在循环中给<div>一个静态(读作:非唯一)ID-HTML规则规定ID必须是唯一的。

此外,如果用户只能选择一个选项,则可能需要使用单选按钮。

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