数据表未显示查询中的所有数据

时间:2018-11-14 17:13:32

标签: php mysql html-table

我有一个查询会产生正确的结果,此后我可以显示记录,但不能以我想要的格式显示。工作格式为学生姓名,年级。我只想连续显示一次学生姓名,然后再显示每个年级。我有显示表时丢失数据的代码。

第一行丢失0个条目。 第二行丢失1个条目。 第三行丢失2个条目。 这种模式会一直持续到查询没有更多数据可获取为止。我有以下代码。

$sql = "SELECT CONCAT(s.last_name, ', ',s.first_name) AS 'Student Name',g.grade 
        FROM `grades` g 
            JOIN assignments a ON a.assignment_id=g.assignment_id 
            JOIN teacher t ON t.teacher_id=a.teacher_id 
            JOIN students s ON s.student_id=g.student_id 
        WHERE a.teacher_id='" . $_SESSION['userId'] . "' 
        AND a.subject_id='2' 
        ORDER BY s.last_name ASC";

$sqlCount = "SELECT COUNT(assignment_name) 
             FROM `assignments` 
             WHERE subject_id = '2' 
             AND teacher_id= '" . $_SESSION['userId'] . "';";

//gets the number of assignments so it can display the table
$resultCount = mysqli_query($connection, $sqlCount);
$countNum = mysqli_fetch_assoc($resultCount);
$counter = $countNum['COUNT(assignment_name)'];
$result = mysqli_query($connection, $sql); 

while($row2 = mysqli_fetch_assoc($result)){
    if($counter == 0){
        echo"<tr><td>{$row2['Student Name']}</td>";
        echo"<td>{$row2['grade']}</td>";
        $counter++;
    } else if($counter < $countNum['COUNT(assignment_name)']){
        echo"<td>{$row2['grade']}</td>";
        $counter++;
    } else{ 
        $counter = 0;
        echo"</tr>";
    }
}

Here is my desired final output format. I had to make it a link due to my account being new

enter image description here

1 个答案:

答案 0 :(得分:0)

这看起来要简单得多。

$sql = "SELECT CONCAT(s.last_name, ', ',s.first_name) AS StudentName,g.grade 
        FROM `grades` g 
            JOIN assignments a ON a.assignment_id=g.assignment_id 
            JOIN teacher t ON t.teacher_id=a.teacher_id 
            JOIN students s ON s.student_id=g.student_id 
        WHERE a.teacher_id='" . $_SESSION['userId'] . "' 
        AND a.subject_id='2' 
        ORDER BY s.last_name,s.first_name ASC";


$result = mysqli_query($connection, $sql); 

$last_stud = null;

while($row2 = mysqli_fetch_assoc($result)){
    if($last_stud != $row2['StudentName']){

        // close previous <tr>
        if ( $last_stud !== null ) {
            echo '</tr>';
        }

        $last_stud = $row2['StudentName'];
        echo"<tr><td>{$row2['StudentName']}</td>";
        echo"<td>{$row2['grade']}</td>";
    } else {
        echo"<td>{$row2['grade']}</td>";
    }
}
echo '</tr>';