dongzha0813 2012-05-08 09:23
浏览 37
已采纳

从数据库中提取包含多个答案的调查

I have a working survey that pulls each question and any related answers from multiple tables. Each question is stored in the following table:

  • tblQuestions, with the fields:
  • qID
  • qText.

The related answers are stored in the table:

  • tblPossAnswers, with the fields:
  • aID
  • qID
  • answerText.

So, I would have 3 possible answers for each question. My sql to pull everything is:

select * from tblQuestions, tblPossAnswers where
tblPossAnswers.qID = tblQuestions.qID
order by tblQuestions.qID ASC

And my PHP to display it:

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'];
}

The problem is this is displaying the qText every time it displays a possible answer. So it looks like:

  • Question 1
  • Possible answer 1
  • Question 1
  • Possible answer 2
  • Question 1
  • Possible answer 3

  • Question 2
  • Possible answer 1
  • Question 2
  • Possible answer 2
  • Question 2
  • Possible answer 3

What I would like to do is have the qText only display when the first possible answer is pulled. I'm still somewhat of a newb to MySQL, so the solution might be something very simple that I'm just not seeing.

  • 写回答

2条回答 默认 最新

  • duanhe6799 2012-05-08 09:26
    关注

    You can either test for whether the question has changed within your PHP loop:

    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'];
    }
    

    Or else you can group the MySQL results by question using GROUP_CONCAT, specifying a separator on which you then split the answers in 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
    

    Then:

    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条)

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大