Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

mehedi's avatar

Get Nested Category And Sub Category

Hi Experts !

I am using MySql Database. And I am now working on Category and Sub Category data handling.

My database table's looks like


| id                | name           | parent_id  |
| ------------- |:-------------- :| -------------:|
| 1                  | Category 1  | null            |
| 2                 | Category 2  |   1                |
| 3                 | Category 3  |    2              |
| 4                 | Category 4  |    2             |
| 5                 | Category 5  |     3             |
| 6                 | Category 6  |    4             |
| 7                 | Category 7  |    4             |

My problem is unlimited category and sub category nesting. I've searched a lot about this at Google. But I can't find any result which can satisfied me.

Now let me say what I want

#Given ID => 4

Expected result

| id                | name           | parent_id  |
| ------------- |:---------------:| -------------:|
| 1                  | Category 1   | null            |
| 2                 | Category 2  |   1                |
| 4                 | Category 4  |    2             |
| 6                 | Category 6  |    4             |
| 7                 | Category 7  |    4             |

That mean's It's return all parent category and all children category.

Thank's

0 likes
1 reply

Please or to participate in this conversation.