PHP & MySQL JOIN's

Discussion in 'PHP' started by crazyryan, Jan 13, 2008.

  1. #1
    Hey

    Need a bit of help with mysql joins and php...

    <?php
                            $query = mysql_query("select * from categories");
                            while($row = mysql_fetch_array($query)) {
                                echo '<li><a href="#">' . $row['name'] . '</a> - (55)</li>';
                            }
                            ?>
    PHP:
    Currently, that's just selecting the name of the category, however where (55) is, I want to display how many files are within that category. I could use 2 queries but think I should learn properly...

    So, categories table has id and the name, e.g.
    ID -- Name
    51 -- Arcade

    Then, I have a files table that has a column called catid, and if the file is in the arcade category, the catid column has 51 in it..

    Hopefully you understand what I'm getting at, but I want to select the amount of total games in a category and the name in one query, any help appreciated.

    Thanks
     
    crazyryan, Jan 13, 2008 IP
  2. Muhammad Haris

    Muhammad Haris Peon

    Messages:
    576
    Likes Received:
    34
    Best Answers:
    0
    Trophy Points:
    0
    #2
    Not sure, sorry.
     
    Muhammad Haris, Jan 13, 2008 IP
  3. crazyryan

    crazyryan Well-Known Member

    Messages:
    3,087
    Likes Received:
    165
    Best Answers:
    0
    Trophy Points:
    175
    #3
    Thanks for the suggestion Haris, anyone else got any ideas?
     
    crazyryan, Jan 13, 2008 IP
  4. SmallPotatoes

    SmallPotatoes Peon

    Messages:
    1,321
    Likes Received:
    41
    Best Answers:
    0
    Trophy Points:
    0
    #4
    Assuming the files table also has an 'id' column which refers uniquely to each file...

    
    $sql = "select categories.name, count(files.id) as count
       from categories, files
       where categories.id = files.catid
       group by categories.name";
    $st = mysql_query($sql) or die(mysql_error());
    while ($row = mysql_fetch_assoc($st))
    {
       echo "<li><a href='#'>{$row['name']}</a> - ({$row['count']})</li>";
    }
    
    PHP:
    Note that this will not display any categories which have zero files. If you want those too, you have to do an outer join.
     
    SmallPotatoes, Jan 13, 2008 IP
    crazyryan likes this.
  5. crazyryan

    crazyryan Well-Known Member

    Messages:
    3,087
    Likes Received:
    165
    Best Answers:
    0
    Trophy Points:
    175
    #5
    Thanks, works perfectly.
     
    crazyryan, Jan 13, 2008 IP