Php - rowspan显示同一行数据库中的所有记录

时间:2012-11-08 09:12:21

标签: php sql html-table

我遇到了rowspan的问题,它将数据库中的所有数据打印成一行! 即使身份不同的人! 输出应该是课程名称和所有参加该课程的学生,将我的代码仅包含在数据库中的第一个课程名称,并将其与数据库中的所有学生姓名一起打印出来!

我的代码是

                      <h2> List of course Name with students names</h2>

<?php


        include('../connect.php');
        $id=$_SESSION['login_user'];


        $sql = "SELECT C.CourseName ,GROUP_CONCAT(s.Studntname) AS Studntname
                FROM course AS c
                INNER JOIN student AS s
                ON s.CourseID = c.CourseID"; 

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


          echo "<center>";

        echo "<table>";
        echo "<tr> <th>Course Name</th> <th> Student Name</th>  </tr>";

        // loop through results of database query, displaying them in the table
        while($row = mysql_fetch_array( $result )) {
                // echo out the contents of each row into a table
               echo "<tr>";

                echo '<td>' . $row['CourseName'] . '</td>';
                echo "<td rowspan='' >" .$row['Studentname'] . "</td>";


                echo "</tr>";


        }
        echo "</table>"; 
         echo "</center>";



?>

我的两张表是:

课程

CourseName var(30)
CourseID   int(7)

学生

Studentname var(30)
StudentID   int(7) 
CourseID    int(7)  

1 个答案:

答案 0 :(得分:0)

问题在于您的查询。您没有使用GROUP BY,这需要指定聚合数据按分组的列(因此名称)。

    $sql = "SELECT C.CourseName ,GROUP_CONCAT(s.Studntname) AS Studntname
            FROM course AS c
            INNER JOIN student AS s ON s.CourseID = c.CourseID
            GROUP BY C.CourseName "; 

当然,如果您需要列出没有人参加的课程,您必须使用LEFT JOIN代替INNER JOIN

    $sql = "SELECT C.CourseName ,GROUP_CONCAT(s.Studntname) AS Studntname
            FROM course AS c
            LEFT JOIN student AS s ON s.CourseID = c.CourseID
            GROUP BY C.CourseName "; 

关于rowspan=''部分 - 我不明白这一点。没有意义。任

  • 不要把它放在那里,使用普通<td>
  • 使用正确的值,如果您需要跨越多行的单元格,例如<td rowspan="2">