在 while 中显示来自 SQL 的单独结果

Displaying a separate result from SQL in while

昨天我了解了 SQL 的 group_concat() 函数之类的东西。我有名为“科目”和“成绩”的表格。在 subjects 中,存储了“id, name, subject_type”,在 grades 中存储了“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里面的apart) 您可以通过将值拆分为用于分隔它的每个字符来获得一个数组:一个逗号。然后你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++;
  }