【问题标题】:Display one-to-many relational result set from PDO query with joined table使用连接表显示 PDO 查询中的一对多关系结果集
【发布时间】:2021-08-15 02:45:52
【问题描述】:

我正在尝试在一个 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> 

【问题讨论】:

标签: php mysql loops pdo one-to-many


【解决方案1】:

你的结果集有类似

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> 

【讨论】:

  • 如果没有变量被传递到 sql 中,则没有理由准备。 SQL 关键字应该大写以提高可读性。我建议多行编写 SQL 以避免水平滚动。
  • 是的,没有必要,但你可以使用它并保留它,因为它也是很好的培训
  • 为了解决我之前提到的问题,我做了 3 处更改: 1- 我在请求和数据库中将“id-question”更改为“idquestion”(因为,我认为 mysql 没有'不接受“-”)。 2- 我应用了你的评论。 3-我写了“?”在回声中(因为当我让它像以前一样时,它会产生问题)。
【解决方案2】:

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

我使用 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> 

【讨论】:

  • @mickmackusa - 因为我没有 QC 我的答案!已修复,谢谢
【解决方案3】:

由于您使用的是 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>';
}

【讨论】:

  • @MARYEM 你有没有欣赏我的精湛技巧?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-10-17
  • 1970-01-01
  • 2018-11-06
  • 1970-01-01
相关资源
最近更新 更多