"> 上面的查询有效,但显示如下: What kind o-6ren">
gpt4 book ai didi

php - 如何限制此 mysql 查询仅显示列数据一次?

转载 作者:行者123 更新时间:2023-11-29 10:51:39 25 4
gpt4 key购买 nike

我需要向用户显示每个问题的所有答案选项,以便他可以选择他的答案。

显示/标记

 <?php 
$i=1;
$surveyQ="SELECT * FROM ve_survey_answers a
JOIN ve_survey_questions q
ON a.QuestionId=q.id";
$surveyResult=mysqli_query($db, $surveyQ);
while($survey=mysqli_fetch_array($surveyResult)){$i++;?>
<div class="div">
<input type="radio" name="useranswer" id="radio<?=$i;?>" class="radio" value='<?=$survey['AnswerId'];?>'/>
<label class="surveylabel" for="radio<?=$i;?>"><?=$survey['Answer'];?></label>
</div>
<?php } ;?>

上面的查询有效,但显示如下:

What kind of pet do you prefer?
Cat
What kind of pet do you prefer?
Dog
What kind of pet do you prefer?
Bird
What kind of pet do you prefer?
Reptile

怎样才能让它显示成这样?

What kind of pet do you prefer?
Cat
Dog
Bird
Reptile

最佳答案

我对您的代码逻辑做了两处更改。首先,我向查询添加了一个 ORDER BY 子句,以便将问题分组在一起。这意味着当您迭代结果集时,给定问题的答案应该以连续的顺序出现。接下来,我添加了一个变量来跟踪当前问题是什么。该问题仅打印一次,在新问题答案 block 的开头。

<?php 
$i=1;
$surveyQ = "SELECT * FROM ve_survey_answers a
INNER JOIN ve_survey_questions q
ON a.QuestionId = q.id
ORDER BY a.QuestionId";
$surveyResult = mysqli_query($db, $surveyQ);
$question = "";
while ($survey=mysqli_fetch_array($surveyResult)) {
$i++;
$curr_question = $survey['Question'];
if ($question != $curr_question) {
$question = $curr_question;
echo "<h5 style='font-weight: bold;'>$question</h5>";
};
echo "<div class=\"div\">
<input type=\"radio\" name=\"useranswer\" id=\"radio<?=$i;?>\" class=\"radio\" value=\"<?=$survey['AnswerId'];?>\"/>
<label class=\"surveylabel\" for=\"radio<?=$i;?>\"><?=$survey['Answer'];?></label>
</div>";
}
?>

关于php - 如何限制此 mysql 查询仅显示列数据一次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43623437/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com