2015-09-09 70 views
1

我使用while循环来输出数据从我的数据库,但我需要在我的情况下,组特定的行我想分组的Student no.Name如图2显示。 像下面的图像我的电流输出的回报: enter image description hereWHILE循环结果在特定的行

这个我想输出:

enter image description here

更新

SQL

$sql = "SELECT * "; 
    $sql .= "FROM registration "; 
    $sql .= "WHERE Sem = '{$sem}' "; 
    if($course !==""){ 
    $sql .= "AND Course = '{$course}' "; 
    } 
    if($year_level !==""){ 
    $sql .= "AND YearLevel = '{$year_level}' "; 
    } 
    $sql .= "AND SY = '{$sy}' "; 
    //$sql .= "GROUP BY StudentNumber "; 
    $sql .= "ORDER BY Lastname, SubjectCode ASC"; 
    $row_set = mysqli_query($con, $sql); 

PHP

<?php if(mysqli_num_rows($row_set)){?> 


    <table class="subjectInProfile" border="0" cellpadding="0" cellspacing="0"> 
    <tr> 
     <th>Student No.</th> 
     <th>Student Name</th> 
     <th>Subject Code</th> 
     <th>Description</th> 
     <th>LecUnit/LabUnit</th> 
    </tr> 
    <?php while($row = mysqli_fetch_assoc($row_set)){ ?> 
    <tr> 
     <td><?php echo htmlentities($row['StudentNumber']); ?></td> 
     <td><?php echo encodeToUtf8($row['LastName'].', '.$row['FirstName']); ?></td> 
     <td><?php echo htmlentities($row['SubjectCode']); ?></td> 
     <td><?php echo htmlentities($row['Description']); ?></td> 
     <td><?php echo htmlentities($row['LecUnit'].'/'.$row['LabUnit']); ?></td> 
    </tr> 
    <?php } mysqli_free_result($row_set); ?> 
    </table> 

    <?php } else { 
    echo "<h1 class=\"noRecordFound\">No record found.</h1>"; 
    }?> 

    <?php } ?> 
+1

请分享一些代码。数据库结构是什么样的? 1桌? 2桌? – Chris

+1

你应该改变查询,而不是尝试在PHP中进行排序。你能显示当前的查询吗? –

+0

您的要求与SQL中的“GROUP BY”无关。您想要抑制某些值的输出以使输出更具吸引力,您应该在PHP/HTML(您的“表示层”)中执行此操作。在SQL分组内用于计算总和值,如总和,平均值,最大值,它不会有条件地抑制值的显示。我建议顺便去掉MySQL标签。 –

回答

0

首先,order by LastName, FirstName, StudentNumber, SubjectCode,以确保一个学生的行是连续的。

然后,只有当您还没有回复学生号码和姓名时才会回显。我会记录回显的最后一个学号,如果当前行的学号不同,请输出它。所以你的代码变成:

. . . 
<?php $lastStudentNumber = null; ?> 
<?php while($row = mysqli_fetch_assoc($row_set)){ ?> 
<tr> 
    <?php if($lastStudentNumber !== $row['StudentNumber']) { ?> 
    <td><?php echo htmlentities($row['StudentNumber']); ?></td> 
    <td><?php echo encodeToUtf8($row['LastName'].', '.$row['FirstName']); ?></td> 
    <?php } else { ?> 
    <td></td> 
    <td></td> 
    <?php } ?> 
    <?php $lastStudentNumber = $row['StudentNumber']; ?> 
    <td><?php echo htmlentities($row['SubjectCode']); ?></td> 
    <td><?php echo htmlentities($row['Description']); ?></td> 
    <td><?php echo htmlentities($row['LecUnit'].'/'.$row['LabUnit']); ?></td> 
</tr> 
<?php } mysqli_free_result($row_set); ?> 
. . .