我有一份工作调查,从多个表中提取每个问题和任何相关答案。每个问题都存储在下表中:
相关答案存储在表格中:
所以,我会为每个问题找到3个可能的答案。我的sql拉一切是:
select * from tblQuestions, tblPossAnswers where
tblPossAnswers.qID = tblQuestions.qID
order by tblQuestions.qID ASC
我的PHP显示它:
while ($row = mysql_fetch_array($result)) {
echo "<p>" . $row['qText'] . "</p><br />";
echo "<input type='radio' name='".$row['qID']."' value='".$row['aID']."' />";
echo $row['answerText'];
}
问题是这是每次显示qText时都显示可能的答案。所以它看起来像:
我想要做的是在第一个可能的答案被拉出时只显示qText。我仍然是MySQL的新手,因此解决方案可能非常简单,我只是没有看到。
答案 0 :(得分:0)
您可以在PHP循环中测试问题是否已更改:
while ($row = mysql_fetch_array($result)) {
if ($row['qID'] != $lastQuestionID) {
echo "<p>" . $row['qText'] . "</p><br />";
$lastQuestionID = $row['qID'];
}
echo "<input type='radio' name='".$row['qID']."' value='".$row['aID']."' />";
echo $row['answerText'];
}
或者您可以使用GROUP_CONCAT
按问题对MySQL结果进行分组,指定一个分隔符,然后在该分隔符上用PHP分割答案:
select *, group_concat(answerText separator char(30)) as answers
from tblQuestions join tblPossAnswers using (qID)
group by tblQuestions.qID
order by tblQuestions.qID ASC
然后:
while ($row = mysql_fetch_array($result)) {
echo "<p>" . $row['qText'] . "</p><br />";
foreach (explode(chr(30), $row['answers']) as $answer) {
echo "<input type='radio' name='".$row['qID']."' value='".$answer."' />";
echo $answer;
}
}
答案 1 :(得分:0)
无需更改sql中的任何内容只需稍微更改php,如下所示
while ($row = mysql_fetch_array($result)) {
if ($row['qText'] != $lastQuestion) {
echo "<p>" . $row['qText'] . "</p><br />";
$lastQuestion = $row['qText'];
}
echo "<input type='radio' name='".$row['qID']."' value='".$row['aID']."' />".$row['answerText'];
}