2015-09-09 114 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); ?> 
. . .