[英]another nested loops php + mysql query
我已经搜索了几个小时,并在foreach循环和while循环上阅读了许多q / a,以获取问题的答案,但尚未找到与查询类似的响应。 大多是分类菜单...
我有这样的mysql表设置
cat | product | link | status
1 | milk | https | in stock
1 | eggs | https | in stock
2 | butter | https | out of stock
2 | bread | https | in stock
3 | bananas | https | in stock
并希望将数据分组到这样的php循环表中;
Category 1
milk | https | in stock
eggs | https | in stock
Category 2
butter | https | out of stock
bread | https | in stock
Category 3
bananas | https | in stock
我需要哪种嵌套循环? 我需要在嵌套循环中按cat
对行进行分组的第二个mysqli查询吗?
谢谢 :)
PHP代码添加编辑
$stmt = $con->prepare("SELECT * FROM wp_products ORDER BY cat");
$stmt->execute();
$results = $stmt->get_result();
echo "<p><center><h4>Master List</h4></center></p>";
echo "<table>
<tr>
<th>Product</th>
<th>Link</th>
<th>Status</th>
</tr>";
if (mysqli_num_rows($results)>0){
while($row = $results->fetch_assoc())
{
echo "<tr><td>" . $row['product'] ."</td>";
echo "<td>". $row['link'] ."</td>;
echo "<td>". $row['status'] ."</td></tr>";
}
}
echo "</table>";
通常情况如下。
这个想法是
代码将像这样。
<?php
$stmt = $con->prepare("SELECT * FROM wp_products ORDER BY cat");
$stmt->execute();
$category = ''; # Default value for category.
$results = $stmt->get_result();
echo "<p><center><h4>Master List</h4></center></p>";
echo "<table>
<tr>
<th>Product</th>
<th>Link</th>
<th>Status</th>
</tr>";
if (mysqli_num_rows($results) > 0) {
while ($row = $results->fetch_assoc()) {
# Category will be updated in this query
if($category != $row['cat']) {
$category = $row['cat'];
echo '<tr><td colspan="3"> Category ' . $category .' </td></tr>';
}
echo "<tr><td>" . $row['product'] . "</td>";
echo "<td>" . $row['link'] . "</td>";
echo "<td>" . $row['status'] . "</td></tr>";
}
}
echo "</table>";
检查。 :)
由于您没有提供任何启动代码,因此未包含任何代码,但是概念很不错,恕我直言。
cat
SELECT MAX(cat) FROM ...
cat
。 在每个循环中,选择与当前循环索引SELECT cat,product,link,status FROM ...
匹配的条目。 循环搜索结果(此处提供DB结果),并构建`
<table> <theader> <tr><th colspan="3">Category $loopindex</th><tr> </theader> <tbody> <tr> <td>$result[product]</td> <td>$result[link]</td> <td>$result[status]</td> </tr> </tbody> </table>
递增+1循环索引
有许多细节需要解决(适当的PHP / HTML代码,表的CSS,如何使用PHP访问数据库等),但是原理可以。
确定,您在我的答案之后添加了代码。
SELECT *
的问题在于您要一次获取整个表。 对于小型数据库可能没问题,但这是您应该避免的习惯。 有一天,您将获得大量数据集(否则这一数据将会增长)。 ORDER BY
值未列在您的结果中(按名称)。 ORDER BY cat
,那么至少您会知道每个条目都是将<table>
html直接输出到页面的正确顺序,而中间没有缓冲机制。 <tr><td colspan="3">Category 1</td></tr>
分隔线。 对评论的询问,询问类别循环。
让我们假设这个表:
name product link status
1 p1 l1 s1
2 p2 l2 s2
1 p3 l3 s3
1 p4 l4 s4
查询SELECT cat,product,link,status FROM table ORDER BY cat,product
将为您提供以下结果集:
1,p1,l1,s1
1,p3,l3,s3
1,p4,l4,s3
2,p2,l2,s2
因此,您可以循环搜索这些结果,一次一行。 每个循环都必须保留下一个循环的cat
值。 如果更改,则在此处放置标题以标识类别。 然后继续打印所有行,直到完成所有行或找到新的类别。 等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.