我遇到了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)
答案 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">