Php 使用联接表显示PDO查询中的一对多关系结果集

Php 使用联接表显示PDO查询中的一对多关系结果集,php,mysql,loops,pdo,one-to-many,Php,Mysql,Loops,Pdo,One To Many,我试图在一个php循环中组合两个mysql表(第一个表用于提问,第二个表用于回答这些问题) 我所拥有的是:我可以显示所有的问题,只有他们的第一个答案(问题是,每个问题都有一个以上的答案) 以下是我的请求和循环代码: <?php $select = $baseblog->prepare('select questions.question,reponses.reponse from questions inner join reponses where questions.id=rep

我试图在一个php循环中组合两个mysql表(第一个表用于提问,第二个表用于回答这些问题)

我所拥有的是:我可以显示所有的问题,只有他们的第一个答案(问题是,每个问题都有一个以上的答案)

以下是我的请求和循环代码:

<?php
$select = $baseblog->prepare('select questions.question,reponses.reponse from questions inner join reponses where questions.id=reponses.id-question and questions.categorie="countries and cities"');
$selecttt = $select->execute(array());
?>
<div class="questions">
    <?php  while ($select1 = $select->fetch()) {?>
        <article>
            <p class="pp"><?php echo $select1['question'] ?> ?</p>
               
            <p><?php echo $select1['reponse'] ?> </p>
        </article>
    <?php } ?>
</div> 

您的结果集有如下内容

question1    answer1
question1    answer2
question1    answer3
question2    answer4
question2    answer5
question2    answer6
question2    answer7
我们将使用它来确定“问题”列中的更改,然后才添加问题

设计需要一些调整

<?php
$select = $baseblog->prepare('SELECTquestions.question,reponses.reponse 
                              FROM questions INNER  JOIN reponses 
                              ON questions.id=reponses.id-question 
                              WHERE questions.categorie="countries and cities"  ');
          $selecttt=$select->execute(array());
   ?>

      <div class="questions">
        <?php  $question = ''; 
         while ($select1=$select->fetch()) {?>
            <article>
                <p class="pp"  ><?php 
                                if ($question != $select1['question']) {
                                  echo $select1['question'];
                                  $question = $select1['question']; 
                                }
                                  ?> ?</p>
               
                <p><?php echo $select1['reponse'] ?> </p>
            </article>
            <?php } ?>
        </div> 

以下是我处理这些问题的方法,如果这不是最好的方法,我期待着从他们的答案中学习最好的方法

我使用两个查询来获取所有数据。对于这个例子,我不准备准备查询,因为没有用户创建的变量可以保护

$mysqli = new mysqli("localhost","my_user","my_password","my_db");
$questionsResult = $mysqli->query("select question, id from questions where categorie='countries and cities'");

$questions = [];
$ids = [];
// loop through to get the ids for our next query
while ($row = $questionsResult->fetch_assoc()) {
    $ids[] = $row['id'];
    $questions[$row['id']]= $row['question'];
}
$questionsResult->free_result(); // save memory

// now get all responses at once and store them under their question ids
$responses = [];
if (count($ids>0) {
     $responsesResult = $mysqli->query("select * from responses where question_id IN (" . implode(",", $ids) . ")");


     while ($row = $responsesResult->fetch_assoc()) {
         if (!isset($responses[$row['question_id']])) $responses[$row['question_id']] = [];
         $responses[$row['question_id']][]= $row;
     }

     $responsesResult->free_result(); // save memory
}
// now you've got everythign ready to go


    <div class="questions">
     <?php  foreach ($questions as $id => $question) {?>
         <article>
             <p class="pp"  ><?php echo $question ?> ?</p>
           <?php if (!isset($responses[$id])) {?>
             <p> No responses found </p>
           <? } else {
             foreach ($responses[$id] as $response) {?>
              <p><?php echo $response['reponse'] ?> </p>
           <?php }
           }?>
         </article>
         <?php } ?>
     </div> 
$mysqli=newmysqli(“本地主机”、“我的用户”、“我的密码”、“我的数据库”);
$questionsResult=$mysqli->query(“从分类为‘国家和城市’的问题中选择问题,id”);
$questions=[];
$ids=[];
//循环获取下一个查询的ID
while($row=$questionsResult->fetch_assoc()){
$ids[]=$row['id'];
$questions[$row['id']=$row['question'];
}
$questionsResult->free_result();//节省内存
//现在,一次获取所有回答并将其存储在问题ID下
$responses=[];
如果(计数($ids>0){
$responseResult=$mysqli->query(“从问题id所在的响应中选择*”);
而($row=$responseResult->fetch_assoc()){
如果(!isset($responses[$row['question\u id']]))$responses[$row['question\u id']]=[];
$responses[$row['question\u id'][]=$row;
}
$responseResult->free_result();//保存内存
}
//现在你已经准备好了一切

没有找到响应


由于您使用的是PDO,我建议使用标志立即在PHP中设置嵌套结果集

未经检验的建议:

$sql = "SELECT q.question, r.reponse 
        FROM questions q
        INNER JOIN reponses r ON q.id = r.`id-question`
        WHERE q.categorie = 'countries and cities'";
$result = $pdo->query($sql)->fetchAll(PDO::FETCH_GROUP);
if ($result) {
    echo '<div class="questions">';
    foreach ($result as $question => $responses) {
        printf(
            '<article>
                 <p class="pp">%s?</p>
                 <p>%s</p>
             </article>',
             $question,
             implode('</p><p>', array_column($responses, 'reponse'))
        );
    }
    echo '</div>';
}
$sql=“选择问题,回答问题
来自问题q
q.id=r.`id问题上的内部连接响应r`
其中q.categorie=‘国家和城市’;
$result=$pdo->query($sql)->fetchAll(pdo::FETCH_组);
如果($结果){
回声';
foreach($结果为$问题=>$回答){
printf(
'

%s

%

', 问题:, 内爆(“

”,数组列($responses,'reponse')) ); } 回声'; }
如果没有变量被传递到sql中,则没有理由进行准备。sql关键字应大写以便于可读。我建议在多行上编写sql以避免水平滚动。是的,没有必要,但您可以使用它,并保留它,因为它也是很好的培训,可以解决我之前提到的问题e,我做了3个改变:1-我在请求和数据库中将“id-question”改为“id-question”(因为,我认为mysql不接受“-”)。2-我应用了你的评论。3-我在echo中写了“?”(因为当我像以前那样让它出现问题)。将dbfiddle演示链接作为美国的一部分可能会对这个问题有所帮助-因为我没有对我的答案进行质量控制!已修复,thanks@MARYEM你有没有考虑过我精湛的技巧?