仅在循环

时间:2016-02-17 11:41:00

标签: php if-statement while-loop

我使用while循环来浏览数据库并提取一些问题和答案。这主要与事实不同,问题顺序是不正确的。

我的问题是如何才能正确打印问题

Eg :

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

这是我的意思的图像:

enter image description here

以下是使用减去查询的代码,因为我知道它有效。我认为if语句错了。

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

1 个答案:

答案 0 :(得分:3)

您的桌子关闭定义不正确。这样做:

$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>';
}