What is wrong with my PHP/MySQL code?
Posted
by James
on Stack Overflow
See other posts from Stack Overflow
or by James
Published on 2010-03-26T23:54:43Z
Indexed on
2010/03/27
0:13 UTC
Read the original article
Hit count: 630
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>";
}
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);
© Stack Overflow or respective owner