1

我的 rowspan 有问题,它将数据库中的所有数据打印到一行中!即使ID不同的那个!输出应该是课程名称和参加该课程的所有学生,把我的代码只取数据库中的第一个课程名称并将其与数据库中的所有学生姓名一起打印出来!

我的代码是

                      <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)  
4

1 回答 1

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">
于 2012-11-08T11:01:16.867 回答