显示类别和子类别php和mysql

时间:2011-11-08 17:19:03

标签: php mysql

mysql_select_db($database_test2, $test2);
$query_Recordset1 = "Select   color.name As color,   item.name As Item,   typ.name As Typ,   color.id From   color Inner Join   item On color.id = item.color_id Inner Join   typ On typ.id = item.typ_id Group By   item.name, typ.name, color.id Order By   color.id, typ.name, item.name";
$Recordset1 = mysql_query($query_Recordset1, $test2) or die(mysql_error());
$row_Recordset1 = mysql_fetch_assoc($Recordset1);
$totalRows_Recordset1 = mysql_num_rows($Recordset1);
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>

<body>
<p><?php echo $row_Recordset1['color']; ?>
</p>
<p><?php echo $row_Recordset1['Typ']; ?></p>
<?php do { ?>
  <p><?php echo $row_Recordset1['Item']; ?></p>
  <?php } while ($row_Recordset1 = mysql_fetch_assoc($Recordset1)); ?>
</body>
</html>
<?php
mysql_free_result($Recordset1);
?>

我使用上面的代码并给出了这个不是我想要的输出

绿色

金属

第1项

第2项

第3项

第4项

第5项

第6项

我想要像这样

绿色

金属

.item 1 木

.item 2

yelow

金属

.item3

.item 4

红色

金属

.item5

.item 6

有人可以帮助我吗

thanx很多

1 个答案:

答案 0 :(得分:1)

在do ... while循环中,只打印项目。你有任何理由使用do..while而不是while循环吗?

这应该有效:

<body>
<?php while ( $row_Recordset1 = mysql_fetch_assoc($Recordset1) ) { ?>
   <p><?php echo $row_Recordset1['color']; ?></p>
   <p><?php echo $row_Recordset1['Typ']; ?></p>
   <p><?php echo $row_Recordset1['Item']; ?></p>
   <?php } ?>
</body>

您还必须删除mysql_fetch_assoc之前的第一个mysql_num_rows

编辑:抱歉,当文字全部在一行时,要求不明确。 由于您获得按颜色排序的行,因此只能输出颜色 与以前不同:

<body>
<?php 
$color = '';
while ( $row_Recordset1 = mysql_fetch_assoc($Recordset1) ) {
   if ( $color != $row_Recordset1[ 'color' ]; ) {
       ?><p><?php echo $row_Recordset1['color']; ?></p><?php
       $color = $row_Recordset1[ 'color' ];
   }
   ?><p><?php echo $row_Recordset1['Typ']; ?></p>
   <p><?php echo $row_Recordset1['Item']; ?></p>
   <?php } ?>
</body>