0

I'm trying to build a friend system for my website and it is set up something like this:

User's Table:
id
name

Friendship Table:
member1
member2

So what I want is that when I have values like this (member1 is the user's id and member2 is the friend's id:

member1 - member2
1           2
1           3
1           5

I want to be able to get all of the user's (id of 1 in example) friend's ids. But when I use mysql_fetch_assoc in PHP I get only one of the member2 ids. So even though the member1 has the ids 2,3 and 5 in his friend list, I can only get one of his friend's ids. Is there any way to fix this so that I can get all of his friend's ids? Thanks

1
  • so, what output do you get? I'm not sure what you mean by 'But when I use mysql_fetch_assoc in PHP I get only one of the member2 ids'. Do you only get one at a time, or one in total? Commented Dec 18, 2011 at 20:42

3 Answers 3

1

As any decent PHP database tutorial would show, call mysql_fetch_assoc() in a loop until it returns false.

Sign up to request clarification or add additional context in comments.

3 Comments

I am using while($row = mysql_fetch_assoc($query)){...} to do it but I still only get one friend id. Any ideas?
You will only get one at a time. If you need to process more than one at a time then you will need to store them and then process after.
I'm not sure I understand, I'm kind of a beginner. Can you please show me what you mean? Thanks
0

Let say you want get friendship table. The table has column: member1 and member2. To get member2 value based on member1,

<?php
$q1 = mysql_query("SELECT * FROM user_table");
while($r1 = mysql_fetch_assoc($q1))
{
    $q2 = mysql_query("SELECT * FROM friendship_table WHERE member1='".$r1['id']."'");
    while($r2 = mysql_fetch_assoc($q2))
    {
        echo $r2['member2'];
    }
}
?>

Or use sql join statement.

<?php
$q = mysql_query("SELECT  * FROM user_table JOIN friendship_table WHERE user_table.id=friendship_table.member1");
while($r = mysql_fetch_assoc($q))
{
    echo $r['member2'];
}
?>

3 Comments

I am using that but I still get only one friend id rather than all the friend ids.
what is your sql query. For that while loop, I will use: "SELECT member1,member2 FROM friendship_table WHERE member1=1", then use while loop for fetch value.
I update my answer, First looping to get member1 ID and second loop, to get member2. Other way, you can use SQL JOIN statement.
0

If processing on the webserver is less of a bottleneck than bandwidth to the MySQL server, use

SELECT GROUP_CONCAT(member2) FROM Friendship where member1=...

and then

$ids=explode(',',$resultfield) 

in PHP

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.