如何使用php检索数据类别?

pdkcd3nj  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(542)

我有一个products表,有三列id、product和category。
我想像这样检索我的产品类别。。
类别1
产品1
产品2
产品3
产品4
类别2
产品1
产品2
产品3
产品4
类别3
产品1
产品2
产品3
产品4
我试过这个。。。

<?php
require_once('config.php');
$conn = mysqli_connect($servername, $username, $password, $dbname);

$sql = "SELECT * FROM `products` WHERE status = 1";

$result = $conn->query($sql);

if (@$result->num_rows > 0) 
{
    while($row = $result->fetch_assoc())
    {
        $category = $row['category'];
        $name = $row['name'];

        foreach ($row as $category) 
        {
            echo $name."<br/>";
        }
    }
}
?>

但每种产品都会重复多次。。。
请帮帮我!

wnvonmuf

wnvonmuf1#

您可以尝试在保存上次遇到的类别的记录的同时循环结果。参见下面的代码(未测试):

<?php
require_once('config.php');
$conn = mysqli_connect($servername, $username, $password, $dbname);

$sql = "SELECT * FROM `products` WHERE status = 1 ORDER BY category ASC, name ASC";

$result = $conn->query($sql);

if (@$result->num_rows > 0) 
{
    $previous_category = ""   // To keep track of the last printed category
    while($row = $result->fetch_assoc())
    {
        $category = $row['category'];
        $name = $row['name'];

        if ($previous_category !== $category) { // If this category has never been printed, we print it
            echo $category."<br/>";
            $previous_category = $category;
        }

        echo $name."<br/>";
    }
}
?>

希望有帮助:)

相关问题