简体   繁体   中英

Php - rowspan shows all records from database at the same row

i've a problem with rowspan , it prints out all the data from the database into one row! even though the one with different id! the output should be Course name and all student that are taken that course , put my code take only the first course name in the database and print it out with all student names in the database!

my code is

                      <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>";



?>

My two tables are:

Course

CourseName var(30)
CourseID   int(7)

Student

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

The problem is with your query. You didn't use GROUP BY , which is needed to specify the column(s) the aggregate data is grouped by (hence the name).

    $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 "; 

Of course, if you need to list courses that no one took, you have to use LEFT JOIN instead of 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 "; 

As for the rowspan='' part - I don't understand this. Doesn't make sense. Either

  • don't put it there, use plain <td>
  • use a correct value, if you need the cell to span multiple rows , like <td rowspan="2">

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM