我有这个表在我的MySQL数据库(只是一个示例)
+----+--------------+---------+--------+-----------+
| id | name | place | number | type |
+----+--------------+---------+--------+-----------+
| 1 | Banana | farm | 100000 | fruit |
| 2 | Apple | park | 100000 | fruit |
| 3 | Eggplant | street | 500 | vegetable |
| 4 | Bitter Gourd | village | 2000 | vegetable |
+----+--------------+---------+--------+-----------+
...
我取数据到我的网页使用PHP,我希望它显示在一个有序的列表类型像这样。
- 水果
- 香蕉|农场| 100000
- apple | park | 100000
- 蔬菜
- 茄子|街道| 500
- 苦瓜|村| 2000
谁能帮我的代码,有很多类型在我的数据库。我已经能够从数据库中获取数据到我的网页。
使用此代码,但我想以相同的方式输出数据。
<?php
$result = mysql_query("SELECT * FROM table;");
while($row = mysql_fetch_array($result)) {
$id = $row['id'];
$name = $row['name'];
$type = $row['type'];
echo "
<tr>
<td>$id</td>
<td>$name</td>
<td>$type</td>
</tr>
";
?>
也许这对你有帮助
<?php
$result = mysql_query("SELECT DISTINCT(type) FROM table");
while($row=mysql_fetch_array($result))
{
echo "<ul>
<li>$row['type']
<ul>";
$result1 = mysql_query("SELECT * FROM table WHERE type=$row['type']");
while($row1=mysql_fetch_array($result1))
{
echo "<li>$row1['name'] | $row1['place'] | $row1['number']</li>";
}
echo "</ul></li></ul>"
?>
MYSQL是已弃用的函数,请使用MYSQLI_* Functions
我个人更喜欢按照我将首先显示的方式重新组织数据,这使得代码可以循环遍历结果并显示它们更具可读性,例如:
<?php
$result = mysql_query("SELECT * FROM table ORDER BY number;");
$produceByType = array();
while ($row = mysql_fetch_array($result)) {
$produceByType[ $row['type'] ][] = $row;
}
?>
<table>
<?php
foreach ($produceByType as $type => $produce):
?>
<tr>
<th colspan="3"><?= $type ?></th>
</tr>
<?php
foreach ($produce as $row): ?>
<tr>
<td><?= $row['name'] ?></td>
<td><?= $row['place'] ?></td>
<td><?= $row['number'] ?></td>
</tr>
<?php
endforeach;
endforeach; ?>
</table>
添加order by子句
select * from table order by type, name;
接下来,将类型放入一个变量中。根据结果中新行的新类型检查该类型。如果相同,则呈现新行,否则关闭该行并插入新行。
<?php
$result = mysql_query("SELECT * FROM table order by type, name;");
$oldtype = "";
while($row=mysql_fetch_array($result))
{
$id = $row['id'];
$name = $row['name'];
$type = $row['type'];
if ($type != $oldtype)
{
echo "
<tr>
<td>$type</td>
</tr>
";
$oldtype = $type;
}
echo "
<tr>
<td>$name</td>
</tr>
";
} ?>
我没有运行代码,但逻辑是正确的。
请使用css将样式应用于缩进值
SQL允许您使用'ORDER BY'子句对数据进行排序
例如按数量/数量排序数据
SELECT * FROM table ORDER BY number;
这将按最小或最大的数量对结果进行排序。另外,
SELECT * FROM table ORDER BY number DESC;
将按数量从大到小对结果进行排序。
在你的情况下,你似乎想按它们排序,然后按数量排序。在这种情况下,你可以输入
SELECT * FROM table ORDER BY type ASC, number DESC;
根据您的选择,相应地修改行中的SQL查询。例如:
$result = mysql_query("SELECT * FROM table;");
$result = mysql_query("SELECT * FROM table ORDER BY type ASC, number DESC;");