Search code examples
phpmysqlloopspdoone-to-many

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


I'm trying to combine two mysql tables (the first table is for questions and the second table is for answers of those questions) in one php loop.

What I have is: I can display all the questions with only their first answer (the trouble is that every question has more than one answer).

Here is my code with the request and the loop:

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

Solution

  • Your result set has something like

    question1    answer1
    question1    answer2
    question1    answer3
    question2    answer4
    question2    answer5
    question2    answer6
    question2    answer7
    

    This we will use to identify changes in questions column and only then add a question.

    The Design will need some adjustments

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