显示PHP多对多关系

时间:2016-12-03 23:01:28

标签: php

大家好我是新来的PHP所以这里是我的代码我在很多很多关系中显示php我在做学生信息系统时遇到了麻烦

这是我的数据库

学生
student_id数据

地址
当然

受试者
subject_id
SUBJECT_NAME
subject_code

student_subject
subject_id
student_id数据

这是我的查询

$sql = "SELECT subject_name
        FROM   subject
             LEFT JOIN student_subject ON (student.student_id = 'student_id')
                    LEFT JOIN subject ON (subject.subject_id = 'subject_id' )";

$records = mysql_query($sql);

现在这是我的代码显示它请帮我如何显示这个例子我只想显示主题名称和主题代码

while($student=mysql_fetch_array($records)){

      echo $student['subject_name'];
      echo $student['subject_code'];
}

这只是样本,因为这只是我想要显示的内容请帮助我,谢谢对不起我的英语不好。无法搜索谷歌中显示多对多关系的任何内容我可以看到一些查询,但我无法搜索我尝试过的代码,但我总是很失败,非常感谢你

所需的输出:

主题名称--- | ---主题代码
ICT ___________ || _________ IT 101
代数_______ || _________ MATH101

删除视觉中的下划线,无法在stackoverflow

中修复新输出

1 个答案:

答案 0 :(得分:0)

<?php

$con = mysql_connect("localhost", "root", "") or die('There is an error to connect DB' . mysql_error());

mysql_select_db('test') or die ('Unable to select DB' . mysql_error());

$query = 'SELECT ST.student_id, ST.name, ST.address, SB.subject_name, SB.subject_code FROM student ST, subject SB, `student_subject` STSB WHERE STSB.student_id=ST.student_id AND STSB.subject_id=SB.subject_id';

$query = mysql_query($query) or die('Unable to execute query' . mysql_error());

if ($query) {
    $str = '';
    $header = '<tr><td>Student ID</td><td>Name</td><td>Address</td><td>Subject</td><td>Subject Code</td></tr>';
    while ($row = mysql_fetch_array($query)) {
        $str .= '<tr>';
        $student_id = $row['student_id'];
        $name = $row['name'];
        $address = $row['address'];
        $subject = $row['subject_name'];
        $subject_code = $row['subject_code'];

        $str .= '<td>' . $student_id . '</td>';
        $str .= '<td>' . $name . '</td>';
        $str .= '<td>' . $address . '</td>';
        $str .= '<td>' . $subject . '</td>';
        $str .= '<td>' . $subject_code . '</td>';
        $str .= '</tr>';
    }
    if ($str) {
        $table = '<table border="1">' . $header      . $str . '</table>';
    } else {
        $tdata = '<tr><td colspan="5">No data found</td></tr>';
        $table = '<table border="1">' . $header . $tdata . '</table>';
    }
    echo $table;
}

输出将如下:

enter image description here