简体   繁体   English

PHP / MySQL-好友列表SQL查询

[英]PHP/MySQL - Friends List SQL Query

I'm going based off this guide in a previous StackOverflow post: 我将在之前的StackOverflow帖子中基于本指南:

"Table Name: User
Columns:
    UserID PK
    EmailAddress
    Password
    Gender
    DOB
    Location

TableName: Friends
Columns:
    UserID PK FK
    FriendID PK FK
    (This table features a composite primary key made up of the two foreign 
     keys, both pointing back to the user table. One ID will point to the
     logged in user, the other ID will point to the individual friend
     of that user)

Example Usage:

Table User
--------------
UserID EmailAddress Password Gender DOB      Location
------------------------------------------------------
1      bob@bob.com  bobbie   M      1/1/2009 New York City
2      jon@jon.com  jonathan M      2/2/2008 Los Angeles
3      joe@joe.com  joseph   M      1/2/2007 Pittsburgh

Table Friends
---------------
UserID FriendID
----------------
1      2
1      3
2      3"

Now, I have all that done, and I've created this query: 现在,我已完成所有工作,并创建了以下查询:

if ($_SESSION["user_id"]) {
    $user_id = $_SESSION["user_id"];
    $query = "SELECT * ";
    $query .= "FROM friends ";
    $query .= "WHERE ";
    $query .= "user_id OR friend_id = '{$user_id}' ";
    $result = mysqli_query($connection, $query);
    $result_set = mysqli_fetch_assoc($result);
    print_r($result_set);

Yay! 好极了! This print_r gets the associated array that I expected. 此print_r获取我期望的关联数组。 But now, because either user_id OR friend_id can be the logged in user, I'm stumped s to what kind of query I need to go with to be able to actually display the friends list. 但是现在,因为user_id或friend_id都可以是登录用户,所以我很困惑必须进行哪种查询才能真正显示朋友列表。

$query = "SELECT * ";
$query .= "FROM users ";
$query .= "WHERE id = ''

This is about as far as I've gotten due to my confusion. 由于我的困惑,这大约是我得到的。 Any point in the right direction would be amazing. 在正确方向上的任何一点都将是惊人的。 thank you! 谢谢!

PHP 的PHP

$reg_no = $_SESSION["user_id"];

SQL QUERY: SQL查询:

select * from `User` join `friends` on '$reg_no' = `friends`.`UserID` and `User`.`UserID` = `friends`.`UserID` or '$reg_no' = `FriendID` and `User`.`UserID` = `friends`.`UserID`;

TRY IT .... 试试吧 ....

Oh I get it. 哦,我明白了。 You (the user) want to display your friends (other users) 您(用户)想显示您的朋友(其他用户)

Try this: 尝试这个:

SELECT U.EmailAddress, U.Gender, U.DOB, U.Location FROM User U
LEFT JOIN Friends F on U.UserID = F.Friend_ID WHERE F.User_ID = 1;

And then just change 1 to whatever the logged in user's id is. 然后只需将1更改为已登录用户的ID。

Cheers! 干杯!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM