2012-10-14 62 views
1

目前我正在試圖以顯示我是誰下面的人的用戶名,問題是,在接下來的過程中,我的唯一的ID和人我正在追蹤被儲存了。談到用戶ID爲名字(單獨的表)在PHP

我就得到了其中顯示ID的點,但我想顯示超鏈接的名稱。 $ p_id是配置文件ID。

下面是我得到了什麼:

$following = mysql_query("SELECT `follower`, `followed` FROM user_follow WHERE follower=$p_id"); 

I am following: <?php while($apple = mysql_fetch_array($following)){ 

      echo '<a href="'.$apple['followed'].'">+'.$apple['followed'].'</a> '; 
      }?> 

的用戶名是在不同的表「用戶」下的字段「用戶名」 - 我需要他們與當前顯示的ID的匹配,以及被顯示。

+0

老'的mysql _ *()'函數計劃棄用,不應該在新的代碼中使用。相反,可以考慮轉向支持準備語句的新API,例如[MySQLi](http://php.net/manual/en/book.mysqli.php)或[PDO](http://php.net/manual/) EN/book.pdo.php)。 –

回答

2

所以,你需要的是一對JOIN S(隱含INNER JOIN)對users,一個在跟隨加入,一個在隨後加入。

SELECT 
    /* Rather than SELECT * you need to be specific about the columns, and 
    give them aliases like followed_name since you have 2 tables with the same 
    column names in the query */ 
    ufollower.id AS follower_id, 
    ufollower.username AS follower_name, 
    ufollowed.id AS followed_id, 
    ufollowed.username AS followed_name 
FROM 
    /* JOIN twice against users, once to get the follower and once to get the followed */ 
    user_follow 
    /* users aliased as ufollower to get the follower details */ 
    JOIN users ufollower ON ufollower.id = user_follow.follower 
    /* users aliased as ufollowed to get the followed details */ 
    JOIN users ufollowed ON ufollowed.id = user_follow.followed 
WHERE 
    user_follow.follower = $p_id 

在您的循環中,名稱可在follower_name, followed_name中找到。

while($apple = mysql_fetch_array($following)){ 
    // Be sure to wrap the name in htmlspecialchars() to encode characters that could break html. 
    // This has the followed id in the href and the followed name in the link text... 
    echo '<a href="'.$apple['followed_id'].'">+'.htmlspecialchars($apple['followed_name']) .'</a> '; 
} 
+0

嘿嘿,謝謝,我只是嘗試了代碼,雖然在第二部分它說,mysql_fetch_array():提供的參數是不符合一個有效的MySQL結果資源(而行) – mobile

+0

@mobile這意味着您的查詢失敗。總是調用'echo mysql_error()'來找出錯誤是什麼。 –

+0

我把你mysql_error提供的查詢代碼(),我得到「警告:mysql_error():提供的參數不是一個有效的MySQL-Link的資源中的」 - 我不明白「用戶名」的任何提及的代碼,我是否需要製作額外的專欄? – mobile

0

您需要將它們連接在一起 - 並且因爲要獨立輸出兩個id的名稱,所以必須將同一個表的兩個雙重連接。

SELECT 
    uf.follower, 
    uf.username AS followerUsername, 
    uf.followed, 
    u2.username AS followedUsername 
FROM 
    user_follow AS uf 
INNER JOIN 
    users AS u1 
ON 
    uf.follower = u1.userID 
INNER JOIN 
    users AS u2 
ON 
    uf.followed = u2.userID 
WHERE 
    follower = ? 

如果您創建SQL語句,請使用預處理語句或轉義!致電mysql_real_escape_string()可以幫助您避免SQL注入攻擊。

+0

仍試圖找出這一點,我得到一個無效的MySQL資源錯誤:( – mobile

相關問題