Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 2 of 2
  1. #1
    New Coder
    Join Date
    Sep 2012
    Posts
    76
    Thanks
    61
    Thanked 0 Times in 0 Posts

    Looping through two tables to produce a list?

    Hello everyone, I am looking to use two tables within a query and output the results in php.

    I have one table which holds details about a group and is called 'groups' with these columns

    group_id
    heading

    I have another table called 'people' who belong to these groups with these columns

    id
    their_name
    group_id

    What I'm looking to do is produce a list in php where I can loop through all the 'groups' and output each heading, then directly underneath that heading output all the their_name that are part of that particular group from the 'people' table.

    Can anyone help here please. At the moment with my scenario I can't even think of the right terms to use a search engine for to find some similar scenarios which would help me, so even anything like that would be helpful. Thank you
    Last edited by Oatley; 01-25-2013 at 07:00 PM.

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,994
    Thanks
    4
    Thanked 2,662 Times in 2,631 Posts
    Join and sort. Display is where it can get tricky since you don't really describe what you want the output to look like.
    PHP Code:
    $sql "SELECT t1.their_name, t2.heading, t2.group_id FROM table1 t1 INNER JOIN table2 t2 ON t2.group_id = t1.group_id ORDER BY t2.group_id ASC";
    if (
    $qry mysql_query($sql))
    {
        
    $iLastGroup 0;
        while(
    $row mysql_fetch_assoc($qry))
        {
            if (
    $iLastGroup != $row['group_id'])
            {
                if (
    $iLastGroup 0)
                {
                    print(
    '</ul>');
                }
                
    printf('<h3>%s</h3>'$row['heading']);
                print(
    '<ul>');
                
    $iLastGroup $row['group_id'];
            }
            
    printf('<li>%s</li>'$row['their_name']);
        }
        print(
    '</ul>');

    Would give you a header and an unordered list. Untested, but looks to work.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 
    Been gone for a few months, and haven't programmed in that long of a time. Meh, I'll wing it ;)

  • Users who have thanked Fou-Lu for this post:

    Oatley (01-25-2013)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •