I am building a navigation menu which lists all my categories and subcategories. The problem is it returns only one of these and not all. I have the categories echoed inside the while loop so I'm not sure why it's only showing one result and not all:
<?php
$query = mysql_query("SELECT * FROM categories_parent");
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$name = $row['name'];
$slug = $row['slug'];
$childStatus = $row['child_status'];
// if has child categories
if ($childStatus == "1") {
echo "<li class='dir'><a href='category.php?slug=$slug'>$name</a>";
echo "<ul id='dropdown'>";
$query = mysql_query("SELECT * FROM categories_child WHERE parent=$id");
while ($row = mysql_fetch_assoc($query)) {
$id = $row['id'];
$name = $row['name'];
$slug = $row['slug'];
echo "<li><a href='category.php?slug=$slug'>$name</a></li>";
开发者_JAVA技巧}
echo "</ul>";
echo "</li>";
}
// if singular parent
else {
echo "<li><a href='category.php?slug=$slug'>$name</a></li>";
}
}
?>
My database tables:
--
-- Table structure for table `categories_child`
--
CREATE TABLE IF NOT EXISTS `categories_child` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(1000) NOT NULL,
`slug` varchar(1000) NOT NULL,
`parent` int(11) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=139 ;
--
-- Dumping data for table `categories_child`
--
INSERT INTO `categories_child` (`id`, `name`, `slug`, `parent`) VALUES
(138, 'Britney Spears', 'category/celiberties/britney-spears/', 137),
(136, 'Tigers', 'category/animals/tigers/', 136),
(137, 'Horses', 'category/animals/horses/', 136),
(135, 'Lions', 'category/animals/lions/', 136);
--
-- Table structure for table `categories_parent`
--
CREATE TABLE IF NOT EXISTS `categories_parent` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(1000) NOT NULL,
`slug` varchar(1000) NOT NULL,
`child_status` int(1) NOT NULL DEFAULT '0',
PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=139 ;
--
-- Dumping data for table `categories_parent`
--
INSERT INTO `categories_parent` (`id`, `name`, `slug`, `child_status`) VALUES
(137, 'Celiberties', 'category/celiberties/', 1),
(138, 'TV Shows', 'category/tv-shows/', 0),
(136, 'Animals', 'category/animals/', 1);
It's because you're redeclaring your $query
and $row
inside your while statement. Therefore your embedded while statement will finish out and then your outer while statement will try to fetch another query from your redeclared $query
line and return false because they have all been executed from the new one. Your old one no longer exists because you overwrote it. You need to use different variable names for your inner while loop, such as $query2
and $row2
.
精彩评论