Can you notice what's wrong with my PHP or MYSQL code?

Posted by Jenna on Stack Overflow See other posts from Stack Overflow or by Jenna
Published on 2010-03-24T02:11:59Z Indexed on 2010/03/24 2:23 UTC
Read the original article Hit count: 424

Filed under:
|

I am trying to create a category menu with sub categories. I have the following MySQL table:

--
-- 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');

And the following 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>";

?>

Now Here's the Problem,

It displays this:

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

I want it to display this:

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

Is there something wrong with my loop? I just can't figure it out.

© Stack Overflow or respective owner

Related posts about php

Related posts about mysql