Dasari Satyam
Dasari Satyam

Reputation: 3

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

}
}

?>

Upvotes: 0

Views: 2194

Answers (2)

Ravinder Reddy
Ravinder Reddy

Reputation: 3879

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

TO display in the HTML table, use the below code

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

Upvotes: 0

Adam Silenko
Adam Silenko

Reputation: 3108

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

Upvotes: 1

Related Questions