2014-09-12 140 views
0

我會根據關本指南中先前StackOverflow的帖子:PHP/MySQL的 - 好友列表SQL查詢

"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  [email protected] bobbie M  1/1/2009 New York City 
2  [email protected] jonathan M  2/2/2008 Los Angeles 
3  [email protected] joseph M  1/2/2007 Pittsburgh 

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

現在,我已經全部完成了,我已經創造了這個查詢:

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); 

耶!這個print_r獲得我期望的關聯數組。 但是現在,因爲user_id或friend_id可以是登錄用戶,所以我很難理解我需要怎樣的查詢來實際顯示好友列表。

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

這是因爲我得到了,因爲我的混亂。 正確方向的任何一點都會令人驚歎。謝謝!

+0

除了沒有'$ user_id'值,你寫的第二個查詢出了什麼問題?什麼返回? – 2014-09-12 19:51:39

回答

0

哦,我明白了。你(用戶)要顯示你的朋友(其他用戶)

試試這個:

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; 

然後只需更改1到任何用戶的id是登錄。

乾杯!

+0

謝謝蒂姆!我從未使用過「你」。格式之前。當你把「從用戶U」,你的「用戶」實際上應該是我的表的名稱,這是「用戶」的小寫字母u,或者是所需的資本? 編輯:哦,即時通訊抱歉。在這個例子中,表格實際上被命名爲。這是我的,名字不同。非常感謝你,我明白了! – diabetesjones 2014-09-12 21:05:55

+0

tim,你認爲theres無論如何可以用英語分解這個MySQL查詢爲我完全執行嗎?我已經在它沒有產生任何錯誤的地方,但是一旦它完成,我仍然無法在這個查詢中得到print_r($ result_set)。編輯:它工作。我工作得很好。非常感謝你tim :) – diabetesjones 2014-09-12 21:18:37

+0

嘿,男人沒問題。這個MySQL查詢所做的是從所有用戶中選擇電子郵件地址,性別,出生日期和位置,然後加入Friends表(使用Friends.Friend_ID = Users.UserID列),然後僅顯示Friends.User_ID = The選定的ID。這是一個更復雜的連接,但我很高興你得到它的工作:) – 2014-09-15 14:31:17

0

PHP

$reg_no = $_SESSION["user_id"]; 

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 ....