php中的子类别
I am doing a project in PHP, MySQL. I need to create a database in which there is a category to which there can be many subcategories ( like for a course book I can have physics, computer science, mathematics etc.).
Also there can be some categories which do not have subcategories (say Mythological Books).
The administrator has to add new category or subcategory via a form in PHP page which then updates the database.
How should I design the structure of my table where if admin for following two cases to be incorporated:
Admin only wants a subcategory to be added then upon selecting its parent category, it should be done.
Admin wants to add a new parent category and there exists no subcategory for it.
Please suggest how should I create my table(s).
我正在用PHP,MySQL做一个项目。 我需要创建一个数据库,其中有一个类别,可以有许多子类别(比如我可以拥有物理,计算机科学,数学等课程书。) p>
可能有一些类别没有子类别(比如神话书籍)。 p>
管理员必须通过PHP页面中的表单添加新的类别或子类别,然后更新数据库。 p>
我应该如何设计我的表的结构,如果要将以下两种情况用于管理员: p>
-
仅限管理员 想要添加子类别然后在选择其父类别时,应该完成。 p> li>
-
管理员想要添加新的父类别,并且不存在子类别。 p> li> ol>
请建议我应该如何创建我的表格。 p> div>
Create a table called 'categories' with columns 'id', 'name', 'parent'.
Then use it like this:
1, Hardware, null
2, Storage, 1
3, Video, 1
4, Harddisks, 2
...
Here is a simple example with books:
Categories table:
+----+--------------------+--------+
| id | name | parent |
+----+--------------------+--------+
| 1 | Comics | NULL |
| 2 | Programming | NULL |
| 3 | SQL/PHP | 2 |
| 4 | Java | 2 |
| 5 | Marvel | 1 |
| 6 | Mythological Books | NULL |
+----+--------------------+--------+
Books table:
+----+---------------------------------------+----------+
| id | name | category |
+----+---------------------------------------+----------+
| 1 | PHP/MYSQL for dummies | 3 |
| 2 | Iron Man and the prisoners of azkaban | 5 |
+----+---------------------------------------+----------+
If you want to show all the books in the Programming>SQL/PHP category you just simply get them with a select query.
mysql> select * from books where category = 3;
+----+-----------------------+----------+
| id | name | category |
+----+-----------------------+----------+
| 1 | PHP/MYSQL for dummies | 3 |
+----+-----------------------+----------+
1 row in set (0,00 sec)