我正在构建一个导航菜单,其中列出了我的所有类别和子类别。问题是它只返回其中之一而不是全部。我在 while 循环内回显了类别,所以我不确定为什么它只显示一个结果而不是全部:
<?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>";
}
}
?>
我的数据库表:
--
-- 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);
最佳答案
这是因为您在 while 语句中重新声明了 $query
和 $row
。因此,您的嵌入 while 语句将完成,然后您的外部 while 语句将尝试从重新声明的 $query
行中获取另一个查询并返回 false,因为它们都已从新查询中执行。你的旧的已经不存在了,因为你覆盖了它。您需要为内部 while 循环使用不同的变量名称,例如 $query2
和 $row2
。
关于php - 我的 PHP/MySQL 代码有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2527539/