Php,为什么我不能使用JOIN在我的表中显示列结果?

时间:2017-01-06 23:22:50

标签: php join

我有一个像这样的“联系人”表:

contact_auto_inc     user_id     contact_id     
      1              1             3
      2              1             5
      3              2             1
      4              3             5
      5              3             2
      6              1             6

和像这样的“用户”表:

 user_id        username
     1          Simon
     2            Bill
     3            Tim
     4          Brendan
     5            Chris
     6            Noel

因此,对于user_id 1,我想打印:

Tim
Chris
Noel

我该怎么做?为什么我的JOIN无法正常工作?

我收到错误“通知:未定义的索引:C:\ wamp64等中的用户名等”

 $select_from_user_table = "SELECT contact_id
FROM contacts
INNER JOIN user
ON contacts.contact_id=user.user_id";

    //get the result of the above
    $result2=mysqli_query($con,$select_from_user_table); 

    while($row = mysqli_fetch_assoc($result2)) {
    echo $row['username']  . "<br>";
}

1 个答案:

答案 0 :(得分:1)

确保选择要使用的列或执行选择*

 $select_from_user_table = "SELECT contact_id, username
FROM contacts
INNER JOIN user
ON contacts.contact_id=user.user_id";

    //get the result of the above
    $result2=mysqli_query($con,$select_from_user_table); 

    while($row = mysqli_fetch_assoc($result2)) {
    echo $row['username']  . "<br>";
}