Вопрос

I have long been searching for an answer to this watched a few videos but I can't seem to find an good answer. I want to make a friend system on my site. I have currently set up a many to many system I think is right. Am I supposed to have one database per member containing all their friends?

but my main problem is when I get all the friend id. how do I get their name? I can connect to the database once for each member using this.

<?php foreach ($friend as $person) {
friend_names[] = mysqli_query($con, "SELECT username FROM users WHERE id='$person'");
} ?>

But is there not a simpler way to do it all in one query. I have tried using the different joins but then its write down all the name in the database not just the logged on users friends. so then I would have to use one database per member containing friends id. and also when I use

SELECT users.username
FROM relationships
INNER JOIN users ON relationships.user_1 = users.id

It adds my username too. could anyone explain how I should do this. so I don't have to sit listen to people on youtube explaining how a function works :S?

DB for the relationships

CREATE TABLE IF NOT EXISTS `relationships` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`user_1` int(11) NOT NULL,
`user_2` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;
Это было полезно?

Решение

select users.username 
from relationships 
inner join users on relationships.user_2=users.id     
and relationships.user_1=2;

you will need to use this in your database. you just change the code at the end (relationships.user_1=2) with your session user id :)

edit: to get it all In one query. I also added a row for status (blocked, friend, pending request):

SELECT users.username
FROM relationships 
INNER JOIN users ON ((relationships.user_1 = users.id AND relationships.user_2='$user')
or (relationships.user_2 = users.id AND relationships.user_1='$user'))
and relationships.status=1
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top