0

I have two tables, in relationship (as you can see in the screenshot):

https://picr.eu/i/wmAT

Now I select from table zerts and want to get all zerts in a list. And now I want to get the username, by the userid. How to access this data which is connected?

$sql = "SELECT * FROM zerts ORDER BY created";
    $result = mysqli_query($conn, $sql);
    while($row = mysqli_fetch_assoc($result)) {
      echo "<tr><td>" . $row["id"] . "</td><td>" . $row["userid"] . "</td><td>" . $row["username"] . "</td></tr>";
    }

Why is this not possible to get the username by the userid? I get a blank output at the username field.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129

2 Answers2

0

You need to create join for this to access username of different table.

$sql = "SELECT zerts.userid,users.username,users.id FROM zerts JOIN users ON users.id = zerts.userid ORDER BY created";
$result = mysqli_query($conn, $sql);
while($row = mysqli_fetch_assoc($result)) {
  echo "<tr><td>" . $row["id"] . "</td><td>" . $row["userid"] . "</td><td>" . 
  $row["username"] . "</td></tr>";
}
EvilsEmpire
  • 146
  • 2
  • 13
0

Please update your query rest of the code will same.

$sql = "SELECT zerts.*,users.username FROM zerts 
LEFT JOIN users ON (zerts.userid = users.id)  ORDER BY zerts.created";

Hope this help.

Mohsin Marui
  • 459
  • 2
  • 8