我有一个这样的“联系人”表:
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
我想要的是打印 contact_ids
的匹配 usernames
。
所以对于 user_id
1,例如,我想打印:
Tim
Chris
Noel
我该怎么做?
我可以打印 contacts
表中的 contact_ids
:
$user_id = $_SESSION['user_id'];
//we want to show contact_ids in the contacts table that have the $user_id above.
$select_from_contacts_table = "SELECT * FROM contacts WHERE user_id = '$user_id'";
//get the result of the above
$result=mysqli_query($con,$select_from_contacts_table);
while($row = mysqli_fetch_assoc($result)) {
$contact_id=$row['contact_id'];
echo $contact_id . "<br>";
}
这将打印:
3
5
6
但是如何在user
表中打印相应的username
列呢?我已经用 INNER JOIN
尝试了几个小时,但不断收到错误和错误的结果,大致如下:
$select_from_user_table = "SELECT DISTINCT contact_id, username
FROM contacts
INNER JOIN user
ON contacts.contact_id=user.user_id WHERE user_id = '$user_id'";
//get the result of the above
$result2=mysqli_query($con,$select_from_user_table);
//show the usernames
while($row = mysqli_fetch_assoc($result2)) {
echo $row['username'] . "<br>";
感谢您的帮助。
最佳答案
您可以在 while 循环中查询用户名,如下所示:
while($row = mysqli_fetch_assoc($result)) {
$contact_id=$row['contact_id'];
$query = "SELECT username FROM user WHERE user_id = '".$contact_id."' ";
$result = mysqli_query($con,$query);
$row = mysqli_fetch_assoc($result)
echo $row['username'];
}
关于php - 使用 PHP,如何获取另一个表中的相应列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41521231/