0

Im using the following code. It goes through a DB and pulls out the question and the related answers.

However it displays the question each time it prints an answer.

How can I make it so the question is only printed once and then the answers are printed.

$qna = mysqli_query($conn, "SELECT q.QText, a.id, a.AText FROM question q INNER JOIN answer a ON q.id = a.Question_ID WHERE q.id=1")  or die(mysqli_error($conn));

while ($data2 = mysqli_fetch_array($qna)) {

echo '<td>'.$data2['QText'].'</td>';

echo '

<table class="layout display responsive-table">
        <thead>
            <tr>
                <th>ID</th>
                <th>Answer</th>
            </tr>
        </thead>
    <tr>
    <td>'.$data2['id'].'</td>
    <td>'.$data['AText'].'</td>
    <td>'.$data['Group_ID'].'</td>
    </table>

';

  }
2
  • Just remove LOOP (WHILE) and make it $data2 = mysqli_fetch_array($qna) Commented Feb 13, 2016 at 11:33
  • @MulhamAryan that does not work Commented Feb 13, 2016 at 11:35

1 Answer 1

1

Select an ID from question table aswell like:

SELECT q.QText, q.id AS QId, a.id, a.AText FROM ...

And then you can print out the question only once using condition:

$lastQuestionID = 0;
while ($data2 = mysqli_fetch_array($qna)) {

if($data2['QId'] != $lastQuestionID)
    echo '<td>'.$data2['QText'].'</td>';

$lastQuestionID = $data2['QId'];

// printing answer here

}
Sign up to request clarification or add additional context in comments.

4 Comments

Notice that the condition should only apply on QText echoing, be sure you didn't wrap printing answer aswell.
my bad , i had a group by bit (experimenting). However it wont print out the AText bit
Iv checked the field is called AText in the DB . It shoudlnt matter that its a varchar
Hey I found a problem . for me it prints the first question , then the second and then the answers to the first so its always a question behind

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.