while循环在mysql内连接中

时间:2018-02-02 02:50:18

标签: php mysql loops join

我的代码使用 INNER JOIN 加入4个表格。使用内连接时我无法自定义循环。如何控制while子句不会发生不需要的循环。

我的代码输出(学生和学校名称在每个主题领域循环播放)

enter image description here

我希望像学生和学校一样循环播放。

enter image description here

我的PHP代码

<table id="customers">
    <?php
        $query=$con->prepare("SELECT subjectcomb.subjectid, subjectcomb.schoolid, student.student, school.school, subject.name 
        FROM ((( subjectcomb
        INNER JOIN school ON subjectcomb.schoolid=school.id)
        INNER JOIN student ON subjectcomb.schoolid=student.schoolID)
        INNER JOIN subject ON subjectcomb.subjectid=subject.id)");
        $query->execute();
        while ($row = $query->fetch(PDO::FETCH_ASSOC)){?>
            <tr>
                <td>
                    <?php echo $row['school']."->".$row['student']?>
                </td>
            </tr>
            <tr>
                <td>
                    <?php echo $row['name']?>
                    <input type="text" name="mark"></input>
                </td>           
            </tr>
        <?php } ?>
</table>

2 个答案:

答案 0 :(得分:1)

尝试在查询中添加ORDER BY

$query=$con->prepare("SELECT subjectcomb.subjectid, subjectcomb.schoolid, student.student, school.school, subject.name 
        FROM ((( subjectcomb
        INNER JOIN school ON subjectcomb.schoolid=school.id)
        INNER JOIN student ON subjectcomb.schoolid=student.schoolID)
        INNER JOIN subject ON subjectcomb.subjectid=subject.id)
        ORDER BY school.school, student.student");

然后在while循环中使用此检查:

<?php
$last_student = ""
while ($row = $query->fetch(PDO::FETCH_ASSOC)){
    if ($last_student != $row['student']) {
?>
    <tr>
        <td>
            <?php echo $row['school']."->".$row['student']?>
        </td>
    </tr>
    <?php } ?>
    <tr>
        <td>
            <?php echo $row['name']?>
            <input type="text" name="mark"></input>
        </td>           
    </tr>
<?php $last_student = $row['student'] } ?>

答案 1 :(得分:0)

我认为菲尔的意思如下。你跟踪以前的学校和学生。如果当前学校和学生与之前相同,则跳过学校/学生排,但如果不相同,则打印出来并更新以前的学校和之前学生的值

$prev_school = '';
$prev_student = '';
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
  if ($row['school'] != $prev_school && $row['student'] != $prev_student) { ?>
    <tr>
      <td>
        <?php echo $row['school']."->".$row['student'] ?>
      </td>
    </tr>
    <?php
    $prev_school = $row['school'];
    $prev_student = $row['student'];
  }
  ?>
  <tr>
    <td>
      <?php echo $row['name']?>
      <input type="text" name="mark"></input>
    </td>           
  </tr>
  <?php 
}