I’m working on a website, and I’m implementing a friend system. People can become friends and that will unlock some stuff which is not important. It is coded in PHP with MySQL as database.
Lets say this is my account table
id | name | picture
0 | Jorik | Cat.jpg
1 | Joost | Fish.jpg
2 | Henk | Ferret.png
This is the friend table(Is this a good way to do this?)
id | user id | friend id | invite date | accepted
0 | 0 | 1 | 123 | 0
1 | 2 | 0 | 456 | 1
2 | 1 | 2 | 123 | 1
The way I check if they are friends is as following (Could be an error in it, but you get the idea).
$fid = friend id, $uid = user id.
WHERE ( (`userid` = '{$uid}' && `friendid` = '{fid}' ) || (`friendid` = '{$uid}' && `userid` = '{$fid}' ))
First of all, is this an efficient way of doing this or is there a better way?
If I wanted to get the list of friends a user has I can run this query
WHERE (`userid` = '{$uid}' || `friendid` = '{$uid}')
now if I would run this query for the user 0, it would return
id | user id | friend id | invite date | accepted
0 | 0 | 1 | 123 | 0
1 | 2 | 0 | 456 | 1
I have worked with MySQL joins before but I can’t figure out how to return something like the following result
id | friend id | invite date | accepted | Name | Picture
0 | 1 | 123 | 0 | Joost | Fish.jpg
1 | 2 | 456 | 1 | Jorik | Ferret.png
It would have to check if it should join the friend id or the user id with id from the account table. (The invited person is the friend id, the one who invited him will get the user id.)
I hope I gave enough information.
Can anyone help me with this?
Thanks in advance,
Jorik
My $0.02:
1) Normalize your data: get rid of the either ‘userid’ or ‘id’. You only need one unique column for accounts.
2) Make a table for ‘friends’ like so:
( approximately )
create table Friends( UserId int unsigned, FriendUserId int unsigned, index( UserId, FriendUserId ));
Then add a row for each ‘friend’ where ‘FriendUserId’ is the account id (see #1) for each person.
3) Make a table for ‘invites’ like so:
(appx)
create table Invites ( UserId int unsigned, FriendId int unsigned, InviteDate datetime default timestamp, Accepted tinyint(1) default 0, primary key( UserId, FriendId ));
Add a row for each invite and update if/when its accepted.
Now to get a persons friends:
select * from Accounts a join Friends f on a.UserId = f.UserId where a.UserId = ;
to get Invites:
select * from Accounts a join Invites i on a.UserId = i.UserId
And so on…
.. but more than anything.. avoid duplicating data ..