简体   繁体   中英

how to get data from two tables from database and display in one html table

I have 2 tables

1)students

students table looks like

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

2)groups

groups table looks like

sl_no         pg_groups

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

i have inserted data into students with groups serial numbers when i am retrieving data from students i will get the groups serial number but what i want is to group names corresponding to the serial number

my code is of retrieving

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

}
}

?>

use join in query like this:

$sql="SELECT stu_slno, pg_groups, stu_name 
  FROM students s
  INNER JOIN groups g ON g.pg_groups = s.stu_gr";
$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>";  

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