友谊系统

时间:2018-04-17 17:11:20

标签: php mysql

我有两张桌子:

users

  • USER_ID
  • USER_NAME
  • ...

friends

  • user_id(发送好友请求的用户)
  • friend_id(收到朋友请求的用户)
  • 确认(1 =朋友,0 =朋友请求)

我希望每个用户都能看到他们的朋友和朋友请求。我有显示朋友用户名的问题。我使它工作,但这是一个糟糕的解决方案,我想只使用一个查询(如果可能)解决这个问题。

我试过了:

    $sql = "SELECT friends.friend_id, friends.user_id, users.user_name FROM friends
            INNER JOIN users ON friends.user_id = users.user_id
            WHERE friends.user_id = " . $_SESSION['user_id'] . " AND confirmed = 1
            OR friends.friend_id = " . $_SESSION['user_id'] . " AND confirmed = 1;";

我的问题是它会在好友表中显示user_nameuser_id相同的user_id用户。我的查询需要检查user_id是否与$_SESSION['user_id']相同,如果相同则必须返回user_nameuser_id相同的用户friend_id friends表格中的string date_time = "2018-04-24 10:00:00"; string[] words = date_time.Split(' ');//Split string string date = words[0];//date = 1st object (before space) string time = words[1];//time= 2nd object (after space)

1 个答案:

答案 0 :(得分:0)

以下列方式制定您的SQL查询,

$sql = "SELECT 
    " . $_SESSION['user_id'] . " as user_id, 
    IF(u2.user_id = " . $_SESSION['user_id'] . ", u1.user_id, f.friend_id) as friend_id, 
    IF(f.user_id = " . $_SESSION['user_id'] . ", u2.user_name, u1.user_name) as friend_username
FROM users as u1
INNER JOIN friends as f
ON u1.user_id = f.user_id
INNER JOIN users as u2
ON f.friend_id = u2.user_id
WHERE (f.user_id = " . $_SESSION['user_id'] . " OR f.friend_id = " . $_SESSION['user_id'] . ") AND f.confirmed = 1";

这是现场演示: http://sqlfiddle.com/#!9/e10252/7

旁注:了解prepared statement因为您的查询现在容易受到SQL注入攻击。另请参阅how you can prevent SQL injection in PHP