我在我的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将数据提取到我的网页上,并希望它按类型显示在一个有序列表中。
- banana | farm | 100000
- apple | park | 100000
- eggplant | street | 500
- bitter gourd | village | 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>
";
?>发布于 2014-08-04 03:10:37
也许这会对你有帮助
<?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_*函数
发布于 2014-08-04 02:39:09
就我个人而言,我更喜欢以我首先显示数据的方式对数据进行重组,这使得代码循环处理结果,并显示它们更容易读,例如:
<?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>发布于 2014-08-04 02:26:07
添加订单分句
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将样式应用于缩进的值。
https://stackoverflow.com/questions/25110942
复制相似问题