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

时间:2018-07-20 13:53:22

标签: php mysql

我有一个产品表,其中有三列 ID 产品类别

我想像这样明智地检索我的产品类别。

类别1

产品1

Product2

Product3

Product4

类别2

产品1

Product2

Product3

Product4

类别3

产品1

Product2

Product3

Product4

我尝试过了...

<?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/>";
        }
    }
}
?>

但是它重复每种产品多次...

请帮助!

1 个答案:

答案 0 :(得分:1)

您可以尝试遍历结果,同时保留最后遇到的类别的记录。 参见下面的代码(未经测试):

<?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/>";
    }
}
?>

希望它会有所帮助:)