PHP while循环显示类别,然后是它下面的产品

时间:2014-10-07 14:57:07

标签: php mysql

我正在尝试根据我们程序中的类别显示产品列表。到目前为止,这是我的代码:

$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>";
    }
}

但显然,我做错了什么。它只显示第一类,然后显示所有产品。帮忙,有人吗?提前谢谢!

1 个答案:

答案 0 :(得分:0)

您不需要第二个循环。这是你的计划中的错误。

应该是这样的:

$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>";
}