显示来自 PDO 查询的一对多关系结果集 table

Display one-to-many relational result set from PDO query with joined table

我正在尝试合并两个 mysql table(第一个 table 用于问题,第二个 table 用于回答这些问题)一个 php 循环。

我所拥有的是:我可以只显示第一个答案的所有问题(问题是每个问题都有多个答案)。

这是我的请求和循环代码:

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

这是我处理这些问题的方法,如果这不是最好的方法,我期待从他们的回答中学习到最好的方法。

我使用 2 个查询来获取所有数据。对于此示例,我不打算准备查询,因为没有用户创建的变量可供保护。

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

由于您使用的是 PDO,我建议使用 FETCH_GROUP 标志以立即在 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>';
}