簡體   English   中英

在 while 中顯示來自 SQL 的單獨結果

[英]Displaying a separate result from SQL in while

您好,我是這些問題的初學者。

昨天我熟悉了 sql 的 group_concat() function 之類的東西。 我有名為“科目”和“成績”的表格。 在科目中存儲“id、name、subject_type”,在成績中存儲“id、grade、subject_type”。

因此,如果科目得到了 subject_type = 1,它將顯示該類型的所有成績。

我創建了這樣的代碼:

<?php 
$sqltest1 = "SELECT s.id AS id,  s.name AS name, group_concat(g.grade SEPARATOR ',') as grades, s.teacher_1 as teacher_1
FROM subjects s 
INNER JOIN grades g ON (g.subject_type = s.subject_type)
GROUP BY s.id"; 
?>
<table class="table table-bordered">
      <thead>
        <tr>
          <th class="col-1">#</th>
          <th class="col-3 text-center">Subject</th>
          <th class="col-6 text-center">Grade</th>
          <th class="col-1 text-center">Options</th>
        </tr>
      </thead>
      <tbody>
    <!-- ###################################################################### -->
      <?php
      $result = $conn->query($sqltest1);
      if ($result->num_rows > 0) {
        $i = 1;

        // output data of each row
        while($row = $result->fetch_assoc()) {
          //$id = $row['id'];
          echo "<tr>";
          echo "<td scope='row'>". $i ."</td>";
          echo "<td>". $row['name'] ."</td>";
          echo "<td><span class='bg-primary'>". $row["grades"] ."</span></td>";
          echo "<td class='text-center'>". $row['teacher_1']."</td>";
          echo "</tr>";
          $i++;
      }
 
    
    } else {
    echo "";
    }
    
    ?>
    
    <!-- ###################################################################### -->
    </tbody>
    </table>

所以我的問題是我無法在一列中檢索單獨的成績。 我想獲得給定類型的所有成績,但要顯示為單獨的成績。

while 應該是這樣的(檢查 while 內部的分隔符)您可以通過將值按用於分隔它的每個字符來拆分值來獲得一個數組:逗號。 然后你foreach所有元素並在里面寫一個span。

    // output data of each row
    while($row = $result->fetch_assoc()) {
      //$id = $row['id'];
      echo "<tr>";
      echo "<td scope='row'>". $i ."</td>";
      echo "<td>". $row['name'] ."</td>"; 

      echo "<td>";
      $arrayGrades = explode(",",  $row["grades"]);
      foreach ($arrayGrades as $grade) {
      echo "<span class='bg-primary'>". $grade ."</span>";
      }
      echo "</td>";
      
      echo "<td class='text-center'>". $row['teacher_1']."</td>";
      echo "</tr>";
      $i++;
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM