开发者

MySQL - How to check if user_id or friend_id are equal to the logged in users ID?

How can I query my database to check if user_id or friend_id are equal to the logged in users ID and that their friendship_status has been accepted.

Here is the MySQL code I got so far.

SELECT COUNT(id) as num 
FROM users_friends 
WHERE users_friends.user_id = '$user_id' 
AND friendship_status = '1'

Here is my MySQL table.

CREATE TABLE users_friends (
id INT UNSIGNED NOT NULL AUTO_INCREMENT,
use开发者_运维问答r_id INT UNSIGNED UNSIGNED NOT NULL,
friend_id INT UNSIGNED NOT NULL,
friendship_status TINYINT(1) UNSIGNED NOT NULL DEFAULT 0,
date_created DATETIME NOT NULL,
);


SELECT COUNT(id) as num 
FROM users_friends 
WHERE (
    user_id = '$sanitized_user_id' 
    OR friend_id = '$sanitized_user_id'
  )
  AND friendship_status = '1'


SELECT    id
FROM      user_friends
WHERE     (user_id = '$logged_in_user_id'
          OR friend_id = '$logged_in_user_id')
          AND friendship_status = 1

If the user_id or friend_id is equal to the logged in uses id and there is a friendship, the returned value will contain corresponding id. If it is not found, then the returned value will be null, which can be checked easily(in MySQL there is probably something like ISNULL(value_to_be_checked) for this).

You must sanitize the logged in user id properly before using it in a query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜