Q:

Only display once in while loop

Im using a while loop to go through a DB and pull out some questions and answers.  That mostly works apart from the facts the the question order isnt correct. 
My question is how do I get the questions to print correctly
Eg :

Q1
Q2
A to Q1
Q3
A to Q2
Blank
A to Q3

Heres an image of what I mean:

Here is the code im using minus the query because I know it works.  I think its the if statement thats wrong. 
    $result = mysqli_query($conn, "SELECT
    q.QText, q.id AS QId, ua.id, a.AText, ca.id, ca. Answer_ID,
    case when a.id = ua. Answer_ID then 'x' else NULL end as IsUserAnswer , 
    case when a.id = ca. Answer_ID then 'x' else NULL end as IsCorrectAnswer 
    FROM user_answers ua
INNER JOIN question q ON q.id = ua. Question_ID
INNER JOIN answer a ON a.Question_ID = q.id 
INNER JOIN correct_answer ca ON ca. Question_ID = q.id 
WHERE ua. Test_ID=1
ORDER BY q.ID") or die(mysqli_error($conn));

     $lastQuestionID = 0;

            while ($data2 = mysqli_fetch_array($result))
        {
        if ($data2['QId'] ! = $lastQuestionID) 

            echo '<p>Q. ' .  $data2['QText'] . ' </p>
        <table class="striped centered">
            <thead>
                <tr>
                    <th>Answer</th>
                    <th>Your Answer</th>
                    <th>Correct Answer</th>
                </tr>
            </thead>';

        $lastQuestionID = $data2['QId'];

        echo '
        <tr>
        <td>' .  $data2['AText'] . ' </td>
         <td>' .  $data2['IsUserAnswer'] . ' </td>
         <td>' .  $data2['IsCorrectAnswer'] . ' </td>
         </tr>';

                }

    echo "</table>";  

A:

Your table closing is defined incorrectly.  Do this instead:
$result = mysqli_query($conn, "Query") or die(mysqli_error($conn));
$lastQuestionID = 0;
$isTableOpen = false;
while ($data2 = mysqli_fetch_array($result)) {
  if ($data2['QId'] ! = $lastQuestionID) {
    if ($isTableOpen) {
       echo '</table>';
    }

    $isTableOpen = true;

    echo '<p>Q. ' .  $data2['QText'] . ' </p>
    <table class="striped centered">
      <thead>
        <tr>
          <th>Answer</th>
          <th>Your Answer</th>
          <th>Correct Answer</th>
        </tr>
      </thead>';
  }

  echo '
  <tr>
  <td>' .  $data2['AText'] . ' </td>
  <td>' .  $data2['IsUserAnswer'] . ' </td>
  <td>' .  $data2['IsCorrectAnswer'] . ' </td>
  </tr>';

  $lastQuestionID = $data2['QId'];    
}

if ($isTableOpen) { // Close last open table
   echo '</table>';
}

