MySQL to select friends/contact list??

Discussion in 'PHP' started by lui2603, Sep 17, 2008.

  1. #1
    I'm making a site where each user has a contact list (of other users on the site).
    The database looks something like:

    Users:
    -user_id
    -username
    etc..

    Contacts:
    -id
    -account_id
    -contact_id

    The problem is the mysql query used to select the contact list for a user..

    say I wanted to list all contacts of a user -by username, not ID.
    At the moment I have:

    
    $getcontacts = mysql_query("SELECT * FROM contacts WHERE account_id='$userid'");
    while($contact = mysql_fetch_assoc($getcontacts)){
     $getuser = mysql_query("SELECT username FROM users WHERE user_id='$contact[contact_id]'");
     $user = mysql_fetch_assoc($getuser);
     echo $user[username].'<br />';
    }
    
    PHP:
    it works.. but isn't doing a seperate query for each contact really inefficient or something?
    How would this normally be done? or would it use a different structure for the db?
     
    lui2603, Sep 17, 2008 IP
  2. mwasif

    mwasif Active Member

    Messages:
    816
    Likes Received:
    23
    Best Answers:
    1
    Trophy Points:
    70
    #2
    Use JOIN
    SELECT users.username FROM users 
    INNER JOIN contacts ON users.user_id = contacts.account_id
    WHERE contacts.account_id='$userid'
    PHP:
     
    mwasif, Sep 17, 2008 IP
    lui2603 likes this.
  3. lui2603

    lui2603 Peon

    Messages:
    729
    Likes Received:
    23
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Ah, thanks for the help!
    I'll look into it ;)
     
    lui2603, Sep 17, 2008 IP
  4. mwasif

    mwasif Active Member

    Messages:
    816
    Likes Received:
    23
    Best Answers:
    1
    Trophy Points:
    70
    #4
    You are weclome
     
    mwasif, Sep 17, 2008 IP