Stephanie Kostova
Stephanie Kostova

Reputation: 88

How to fetch results in while loop

I have the following 2 tables.

| ID | Name        | Category |
|----|-------------|----------|
|  1 | Foo bar     | 3        |
|  2 | Bar foo     | 2        |
|  3 | Baz Foo     | 3        |
|  4 | Baz Foo2    | 1        |
|  5 | Baz Foo3    | 1        |
|  3 | Baz Foo     | 1        |

| ID | Category_name |
|----|---------------|
|  1 | Cat 111       | 
|  2 | Cat 222       | 
|  3 | Cat 3333      | 

I want to display all categories with counter, example:

Cat111 - 3
Cat222 - 2
Cat333 - 2

I tried to do it by the following way, but its not working:

$query = mysqli_query('SELECT * FROM gallery');

while($row = mysqli_fetch_assoc($query)) {
    $query_cat = mysqli_query($conn, "SELECT * FROM `pics_cat` WHERE id = '".$row['category']."' GROUP BY category_name"); 
    $rowCat = mysqli_fetch_assoc($query_cat);
    echo $rowCat['category_name'];
    echo $rowCat['cnt'];
}

Upvotes: 2

Views: 1202

Answers (1)

Andrea Olivato
Andrea Olivato

Reputation: 2545

You are not sharing the names of the tables, but I assume the first one is Gallery and the second one is pics_cat

If your tables are not going to be very large, I suggest you to solve everything with a single join query, which simplifies the logic of your script.

$query = mysqli_query($conn, 'SELECT p.Category_name,COUNT(g.ID) AS cnt FROM `gallery` AS g LEFT JOIN `pics_cat` AS p ON p.ID = g.Category GROUP BY p.ID');

while($row = mysqli_fetch_assoc($query)) {
    echo $rowCat['Category_name'];
    echo $rowCat['cnt'];
}

If you prefer to do this with 2 queries in a loop, it's much easier to start from the Category table and then move to the gallery

$query = mysqli_query($conn, 'SELECT * FROM `pics_cat` ORDER BY ID');

while($row = mysqli_fetch_assoc($query)) {
    $query_count = mysqli_query('SELECT COUNT(ID) AS cnt FROM `gallery` WHERE Category = '.$row['ID'].'');
    $row_count = mysqli_fetch_assoc($query_count);
    echo $row['Category_name'];
    echo $row_count['cnt'];
}

Upvotes: 2

Related Questions