gpt4 book ai didi

php - 使用 PHP+MySQL 显示带有子类别和 n-sub 类别的类别

转载 作者:行者123 更新时间:2023-11-29 04:23:26 25 4
gpt4 key购买 nike

我的代码有问题。显示具有 n 个子类别的所有类别的最佳方式是什么?

我的 MySQL 数据库如下所示:

CREATE TABLE categories ( 
category_id INT UNSIGNED NOT NULL AUTO_INCREMENT,
parent_id INT UNSIGNED NOT NULL DEFAULT 0,
name TEXT NOT NULL,
user INT NOT NULL,
PRIMARY KEY (category_id),
INDEX parent (parent_id)
);

其中 user 是来自另一个表的 id(如果类别有 user = '2'id = '2' 的用户可以看到那个类别)

category_id   parent_id   name                   user
1 0 Main category 1 2
2 1 Subcategory 1 2
3 1 Subcategory 2 2
4 3 SubSubcategory 1 2

我的 php 代码:

<?php 
include('config.php'); //Mysql connect file
//get id from user

if($_GET['id'] != $user_id) {

$id = $_GET['id'];

//check to make sure the user is an admin, who can change mysql

$result = mysql_query("SELECT * FROM users WHERE username = '$username' AND admin = '1'");

$rowCheck = mysql_result($result, 0);



//if the query returns a number, we know the user is an admin. And here we can VIEW our categories

if($rowCheck > 0) {

$user_result = mysql_query("SELECT * FROM users, categories WHERE id = '$id'");

while($row = mysql_fetch_array($user_result)) { ?>

<ol>
<li><a href=""><?php echo $row['name']; ?></a></li>
</ol>

<?php }

} else {

echo "You are not admin";
}
//bla bla bla etc.
...
}

如何查看类

<ol>
<li>
<a href="">Main category 1</a>
<ol>
<li><a href="">Subcategory 1</a></li>
<li><a href="">Subcategory 2</a>
<ol>
<li><a href="">Subsubcategory 1</a></li>
</ol>
</li>
</ol>
</li>
</ol>

最佳答案

试试这个

$result = mysql_query("SELECT * FROM users WHERE username = '$username' AND admin = '1'");

$rowCheck = mysql_result($result, 0);

//if the query returns a number, we know the user is an admin. And here we can VIEW our categories

if($rowCheck > 0) {

//First fetch only parent categories
$first_level_cats = mysql_query("SELECT * FROM categories WHERE user = '$id' AND parent_id = 0");
echo '<ol>';
while($row = mysql_fetch_array($first_level-cats)) { ?>

<li><a href=""><?php echo $row['name']; ?></a></li>

<?php
$second_level_cats = mysql_query("SELECT * FROM categories WHERE user = '$id' AND parent_id = $row['id']");
echo '<ol>';
while($row = mysql_fetch_array($second_level-cats)) { ?>

<li><a href=""><?php echo $row['name']; ?></a></li>
<?php
$third_level_cats = mysql_query("SELECT * FROM categories WHERE user = '$id' AND parent_id = $row['id']");
echo '<ol>';
while($row = mysql_fetch_array($sthird_level-cats)) { ?>

<li><a href=""><?php echo $row['name']; ?></a></li>
<?php
}
echo '</ol>'; //third level close
?>
}
echo '</ol>'; // second level close
?>
<?php }
echo '</ol>'; // first level close
} else {

echo "You are not admin";
}
//bla bla bla etc.
...
}

我已尽力解决您的查询,根据您的架构交叉检查表名和列

尝试使用Mysqli扩展名而不是 Mysql

关于php - 使用 PHP+MySQL 显示带有子类别和 n-sub 类别的类别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17164165/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com