如何从数据库中的两个表中获取数据并显示在一个html表中

时间:2016-04-06 14:55:29

标签: php mysql mysqli

我有2张桌子

1)的学生

学生表看起来像

stu_slno        stu_gr           stu_name
1               1                ABCDESDFDGFJ
2               3                KJJJHJILKJBJB
3               5                HAHAHAHAHKJHKJH
4               1                BBJHBAHJBHJBAJHK

2)基团

组表看起来像

sl_no         pg_groups

1             01-M.A HISTORY
3             03-M.A SOCIOLOGY
5             04-M.A ECONOMICS

我已将数据插入到具有组序列号的学生中 当我从学生那里检索数据时,我会得到群组序列号,但我想要的是对应于序列号的群组名称

我的代码是检索

<?PHP
$sql="SELECT * FROM students";
if ($us=$conn->query($sql)){;
if ($us->num_rows > 0) {
echo '<table border="2">';

    echo "<tr>";

        echo "<th>Slno</th>";

        echo "<th>Name</th>";

        echo "<th>Group</th>";

    echo "</tr>";
while($row = $us->fetch_assoc()) {
    echo "<tr>";

    echo "<td>" .$i++. "</td>";

    echo "<td>" .$row['stu_name']. "</td>";

    echo "<td>" .$row['stu_gr']. "</td>";   
    echo "</table>";
}

}
}

?>

2 个答案:

答案 0 :(得分:1)

在这样的查询中使用join:

$sql="SELECT stu_slno, pg_groups, stu_name 
  FROM students s
  INNER JOIN groups g ON g.pg_groups = s.stu_gr";

答案 1 :(得分:0)

$sql = "SELECT s.*, g.pg_groups from students AS s LEFT JOIN groups as g ON g.sl_no = s.stu_gr";

要在HTML表格中显示,请使用以下代码

echo "<td>" .$row['pg_groups']. "</td>";  
相关问题