简体   繁体   中英

Displaying Multiple values from a Junction table with Explode in PHP MySQL

I'm working on school project. Where I have made a junction table for a Teacher and Subjects . The Teacher table contains the t_id and t_name and the Subjects table contains the sub_id and sub_name. Whereas in the junction name I have made foreign keys of t_id and sub_id. Now when I choose multiple subjects and then display it in the UI. It repeats the t_id 3 times if I select 3 subjects. I just want to show the t_id once with the 3 sub_id with comma that separates them in a table. Click here to see the screenshot of the current table .

This is the current code I have written:

<?php

    $que = "select teacher.t_name,teacher.qualification,teacher.gender,subject.sub_name from teacher join teach_sub_junction on teacher.t_id=teach_sub_junction.teacher_id join subject on subject.sub_id=teach_sub_junction.subject_id";
    $i = 1;

        if($row = mysql_query($que)){

            while($result = mysql_fetch_assoc($row)){
                 $tname = $result['t_name'];
                 $qualification = $result['qualification'];
                 $gender = $result['gender'];
                 $sub_name = $result['sub_name'];
                 ?>

            <tr>
                <td><?php echo $i; $i++; ?></td>
                <td><?php echo $tname; ?></td>
                <td><?php echo $gender; ?></td>
                <td><?php echo $qualification; ?></td>
                <td><?php echo $sub_name; ?></td>
            </tr>
<?php       }
        }
?>  

You can GROUP_CONCAT(subject.sub_id) and GROUP BY teacher.t_id to show the t_id once with the 3 sub_id with comma that separates them in a table.

Refer : GROUP BY clause to get comma-separated values in sqlite

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