doudun6928 2017-03-26 19:20
浏览 11
已采纳

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:

  1. Admin only wants a subcategory to be added then upon selecting its parent category, it should be done.

  2. Admin wants to add a new parent category and there exists no subcategory for it.

Please suggest how should I create my table(s).

  • 写回答

1条回答 默认 最新

  • dqrqp8492 2017-03-26 19:37
    关注

    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)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 win10权限管理,限制普通用户使用删除功能
  • ¥15 minnio内存占用过大,内存没被回收(Windows环境)
  • ¥65 抖音咸鱼付款链接转码支付宝
  • ¥15 ubuntu22.04上安装ursim-3.15.8.106339遇到的问题
  • ¥15 求螺旋焊缝的图像处理
  • ¥15 blast算法(相关搜索:数据库)
  • ¥15 请问有人会紧聚焦相关的matlab知识嘛?
  • ¥15 网络通信安全解决方案
  • ¥50 yalmip+Gurobi
  • ¥20 win10修改放大文本以及缩放与布局后蓝屏无法正常进入桌面