你能注意到我的PHP或MYSQL代码有什么问题吗?

时间:2010-03-24 02:12:00

标签: php mysql

我正在尝试使用子类别创建一个类别菜单。我有以下MySQL表:

--
-- Table structure for table `categories`
--

CREATE TABLE IF NOT EXISTS `categories` (
  `ID` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(1000) NOT NULL,
  `slug` varchar(1000) NOT NULL,
  `parent` int(11) NOT NULL,
  `type` varchar(255) NOT NULL,
  PRIMARY KEY (`ID`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 AUTO_INCREMENT=66 ;

--
-- Dumping data for table `categories`
--

INSERT INTO `categories` (`ID`, `name`, `slug`, `parent`, `type`) VALUES
(63, 'Party', '/category/party/', 0, ''),
(62, 'Kitchen', '/category/kitchen/', 61, 'sub'),
(59, 'Animals', '/category/animals/', 0, ''),
(64, 'Pets', '/category/pets/', 59, 'sub'),
(61, 'Rooms', '/category/rooms/', 0, ''),
(65, 'Zoo Creatures', '/category/zoo-creatures/', 59, 'sub');

以下PHP:

<?php

include("connect.php");

echo "<ul>";

$query = mysql_query("SELECT * FROM categories");

while ($row = mysql_fetch_assoc($query)) {

    $catId   = $row['id'];
    $catName = $row['name'];
    $catSlug = $row['slug'];
    $parent  = $row['parent'];
    $type    = $row['type'];

    if ($type == "sub") {

        $select = mysql_query("SELECT name FROM categories WHERE ID = $parent");

        while ($row = mysql_fetch_assoc($select)) {
            $parentName = $row['name'];
        }

        echo "<li>$parentName >> $catName</li>";

    }
    else if ($type == "") {
        echo "<li>$catName</li>";
    }

}

echo "</ul>";

?>

现在这是问题,

显示:

* Party
* Rooms >> Kitchen
* Animals
* Animals >> Pets
* Rooms
* Animals >> Zoo Creatures

我想要它显示:

* Party
* Rooms >> Kitchen
* Animals >> Pets >> Zoo Creatures

我的循环有问题吗?我只是想不出来。

3 个答案:

答案 0 :(得分:2)

“动物园生物”和“宠物”都有“动物”(59)作为其父母 要做你想做的事,你可能需要将'Pets'设置为'Zoo Creatures'的父级 为此,用以下内容替换最后一行SQL:

(65, 'Zoo Creatures', '/category/zoo-creatures/', 64, 'sub');

答案 1 :(得分:1)

将您的第一个选择语句更改为:

SELECT * FROM categories WHERE parent = 0

您还需要递归调用$ type ==“sub”代码中的代码。

您的类型字段似乎与父字段的功能重复。如果菜单项有父项,则不是子菜单吗?

答案 2 :(得分:1)

echo '<ul>';

$parents = mysql_query('SELECT * FROM categories WHERE parent = 0');

while ($row = mysql_fetch_assoc($parents)) {
  $catId = $row['ID'];
  $catName = $row['name'];
  $catSlug = $row['slug'];
  $parent = $row['parent'];
  $type = $row['type'];

  $output = "<li>$catName";
  $children = mysql_query("SELECT name FROM categories WHERE parent = $catId");
  while ($child = mysql_fetch_assoc($children)) {
    $childName = $child['name'];
    $output .= " &gt;&gt; $childName";
  }

  $output .= '</li>';

  echo $output;
}

echo '</ul>';