php - 在 PHP MySQL 中使用 Explode 显示连接表中的多个值

标签 php mysql database

我正在做学校项目。我为教师科目制作了一个联结表。 Teacher 表包含 t_id 和 t_name,Subjects 表包含 sub_id 和 sub_name。而在连接名称中,我创建了 t_id 和 sub_id 的外键。现在,当我选择多个主题然后将其显示在用户界面中时。如果我选择 3 个科目,它会重复 t_id 3 次。我只想显示一次 t_id 和 3 个 sub_id,并在表中用逗号分隔它们。 Click here to see the screenshot of the current table

这是我当前编写的代码:

<?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       }
        }
?>  

最佳答案

您可以使用 GROUP_CONCAT(subject.sub_id) 和 GROUP BY Teacher.t_id 来显示一次 t_id,并在表格中用逗号分隔 3 个 sub_id。

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

关于php - 在 PHP MySQL 中使用 Explode 显示连接表中的多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43704470/

相关文章:

php - 如何在 html 按钮上单击调用 php 脚本/函数

mysql - 删除与 2 加入得到错误 - mysql

php - 将下拉菜单中的值保存到数据库(php、mysql)

database - 我有10个数据库表,其中6个是链接表,我应该制作一个通用的LinkTable吗?

php - PHP正则表达式匹配首次出现?

php - 方法 Illuminate\Support\Collection::offset 不存在

php - 当我获取/转储列表时,redis (PHP) 中的 LPUSH 函数抛出 bool(false)

mysql - 无法在 CentOS-7 上安装 mysql-devel

php - 使用 PHP 从 MySQL 获取 UTF-8 字符串

mysql - 在数据库中存储大量大型整数数组的有效方法