我正在尝试让用户朋友列表显示在他们的个人资料页面上,但我可以显示的是用户个人资料的名称,而不是他们的任何朋友或个人资料图片。
我的表格如此
USERS
user_id
username
profile
FRIENDS
user_id
friend_id
accepted (ENUM 0 for no, 1 for accepted).
以下是我正在使用的代码,我还没有开始将我的网站转换为MYSQLI,所以是的,我知道代码目前很容易受到攻击。
<?php
$user_id = $_SESSION['user_id'];
$sql = "SELECT friends.id, friends.user_id, friends.friend_id, friends.accepted, users.user_id, users.username, users.profile
FROM `friends`
LEFT JOIN `users` on users.user_id = friends.user_id OR users.user_id = friends.friend_id
WHERE friends.friend_id = $user_id OR friends.user_id = $user_id
AND users.user_id != $user_id AND friends.accepted = '1' OR friends.friend_id = $user_id AND friends.accepted = '1'";
$result = mysql_query($sql);
?>
<img src="<? echo $profile; ?>"><? echo $username; ?>
感谢您的任何提示。
答案 0 :(得分:1)
试试这个。
<?php
$friends_result = mysql_query("
SELECT
users.`username` AS username
FROM
friends
LEFT JOIN
users
ON
users.`user_id` = friends.`user_id`
OR
users.`user_id` = friends.`friend_id`
AND
users.`user_id` != '" . $user_id . "'
WHERE
friends.`user_id` = '" . $user_id . "'
OR
friends.`friend_id` = '" . $user_id . "'");
while($friends_array = mysql_fetch_array($friends_result))
{
echo $friends_array['username'] . "<br />";
}
?>
答案 1 :(得分:0)
尝试使用此查询
SELECT friend_id as id FROM `friends` where user_id=$user_id and accepted=1 union select user_id as id from friends where friend_id=$user_id and accepted=1
以上查询将返回好友ID
答案 2 :(得分:0)
尝试使用
编辑命令$result = mysql_query($sql) or die(mysql_error());
如果您收到任何错误,请注意?
如果您在语法中遇到任何错误,请更正。
答案 3 :(得分:0)
假设fiends表中的user_id和friend_id是users表中user_id的外键,那么关系将是“用户可以拥有一个或多个朋友”。以下查询将为您提供特定用户的朋友ID
SELECT friend_id from friends f
JOIN users u ON f.user_id = u.user_id
WHERE u.user_id = $user_id AND f.accepted = 1
答案 4 :(得分:0)
尝试以下查询
SELECT users.id as userid, firstname, lastname, username,profile_id,friends.accepted FROM users RIGHT JOIN (SELECT friend_id as id,accepted FROM `friends` where user_id=$user_id and accepted=1 union select user_id as id,status from friends where friend_id=$user_id and accepted=1) friends ON users.id = friends.id;
答案 5 :(得分:-1)
$ result = mysql_query($ sql)或die(mysql_error());
试一下,然后给我们输出。
此致