Gat Orade
Gat Orade

Reputation: 3

PHP while loop to display categories then products under it

I am trying to display the list of products depending on the categories they are under in my program. So far this is what my code looks like:

$query = "SELECT products_name, categories_desc, id, price
        FROM products, categories
        WHERE products.categories_id = categories.categories_id";

$result = mysql_query($query);

while($row=mysql_fetch_array($result)){
    echo "<b>" . $row['categories_desc'] . "</b><br>";

    while($row=mysql_fetch_array($result)){
        echo "<input type='checkbox' name='" . $row['products_name'] . "' value='" . $row['price'] . "'>" . $row["products_name"] . "</br>";
    }
}

But obviously, I am doing something wrong. It only displays the first category then all the products. Help, anyone? Thanks in advance!

Upvotes: 0

Views: 1630

Answers (1)

Serpes
Serpes

Reputation: 672

You don't need the second loop. It is what it's wrong in your program.

It should be something like:

$query = "SELECT products_name, categories_desc, id, price
        FROM products, categories
        WHERE products.categories_id = categories.categories_id";

$result = mysql_query($query);
$last_category='';
while($row=mysql_fetch_array($result)){
    if ($last_category!=$row['categories_desc']){
        echo "<b>" . $row['categories_desc'] . "</b><br>";
        $last_category=$row['categories_desc'];
    }

    echo "<input type='checkbox' name='" . $row['products_name'] . "' value='" . $row['price'] . "'>" . $row["products_name"] . "</br>";
}

Upvotes: 1

Related Questions