gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 07:30:37 25 4
gpt4 key购买 nike

我有一个产品表,其中包含三列IDProductCategory

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

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

但是每个产品重复了很多次...

请帮忙!

最佳答案

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

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

希望对您有所帮助:)

关于php - 如何使用 php 检索数据类别明智?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51444109/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com