在 PHP 中将用户 ID 转换为名称(单独的表) [英] Turning user ID into name (separate tables) in PHP
问题描述
我目前正在尝试显示我关注的人的用户名,问题是在接下来的过程中,只存储了我和我关注的人的 ID.
I am currently trying to display the username of people who i am following, the problem is that during the following process, only the ID of me and the person i'm following is stored.
我已经到了显示 ID 的地步,但我想显示超链接的名称.$p_id 是个人资料 ID.
I've got it to the point where the ID's are displayed but i'd like to show the names hyperlinked. $p_id is the profile 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 匹配并显示.
The usernames are in a different table "users" under the field "username" - I need them to match up with the ID's that are currently displayed, and be displayed.
推荐答案
所以你需要的是一对 JOIN
(隐式 INNER JOIN
)和 用户
,一个加入关注者,一个加入被关注者.
So what you need is a pair of JOIN
s (implicitly INNER JOIN
) against users
, one to join in the follower and one to join in the followed.
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,follower_name
中可用.
In your loop, the names are available in 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> ';
}
这篇关于在 PHP 中将用户 ID 转换为名称(单独的表)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!