PHP mySQL表比较两列

时间:2016-11-19 05:27:20

标签: php mysql

我需要比较两个表之间的数据。

t1 = playerachievements

| ID |用户名|成就ID |

t2 =成就

| ID |成就名称|图像位置|

现在我在t1中搜索与登录用户的用户名匹配的项目

$sql = "SELECT * FROM playerachievement WHERE username = '$user'";

现在我需要做的是根据t1中的成就ID和t2中的ID

获取用户所拥有的每项成就的图像位置

最好的方法是什么?

编辑:

我想我几乎拥有它,但这只会带来一个结果:

$sql = "SELECT * FROM playerachievement WHERE username = '$user'";

$result = $db_conn->query($sql);
if ($result->num_rows > 0) {
    // output data of each row
    while($row = $result->fetch_assoc()) {
        $achid = $row['achievement'];
    }

    $sql = "SELECT * FROM achievements WHERE id = '$achid'";
    $result = $db_conn->query($sql);
    if ($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
                echo "<div class='custom-container'>
                        <img src='".$row["image"]."'</img></div>";
            }
    }
}

1 个答案:

答案 0 :(得分:0)

要检查每个值,您应该在while loop

中给出条件
$sql1 = "SELECT * FROM playerachievement WHERE username = '$user'";
$result1 = $db_conn->query($sql1);
if ($result1->num_rows > 0) {
// output data of each row
 while($row1 = $result1->fetch_assoc()) {
    $achid = $row1['achievement'];

  $sql2 = "SELECT * FROM achievements WHERE id = '$achid'";
  $result2 = $db_conn->query($sql2);
  if ($result2->num_rows > 0) {
          while($row2 = $result2->fetch_assoc()) {
              echo "<div class='custom-container'>
                      <img src='".$row2["image"]."'</img></div>";
          }
  }
 }
}