Well, as far as I can see you have two choices, both well known.
1) You make a recursive function, just the ones you have been trying. There are tons of them around and i won't put him in here.
2) By far my favourite, this is the Database pattern most modern ORM use, it's called nested set model.
Basically you create a few more columns on the table, it should look like this one:
CREATE TABLE nested_category (
category_id INT AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(20) NOT NULL,
lft INT NOT NULL,
rgt INT NOT NULL
);
INSERT INTO nested_category VALUES(1,'ELECTRONICS',1,20),(2,'TELEVISIONS',2,9),(3,'TUBE',3,4),
(4,'LCD',5,6),(5,'PLASMA',7,8),(6,'PORTABLE ELECTRONICS',10,19),(7,'MP3 PLAYERS',11,14),(8,'FLASH',12,13),
(9,'CD PLAYERS',15,16),(10,'2 WAY RADIOS',17,18);
SELECT * FROM nested_category ORDER BY category_id;
+-------------+----------------------+-----+-----+
| category_id | name | lft | rgt |
+-------------+----------------------+-----+-----+
| 1 | ELECTRONICS | 1 | 20 |
| 2 | TELEVISIONS | 2 | 9 |
| 3 | TUBE | 3 | 4 |
| 4 | LCD | 5 | 6 |
| 5 | PLASMA | 7 | 8 |
| 6 | PORTABLE ELECTRONICS | 10 | 19 |
| 7 | MP3 PLAYERS | 11 | 14 |
| 8 | FLASH | 12 | 13 |
| 9 | CD PLAYERS | 15 | 16 |
| 10 | 2 WAY RADIOS | 17 | 18 |
+-------------+----------------------+-----+-----+
If you notice there is no parent_id column. To be able to search for it's childrens for, let's say row 5 the query will be like:
Select * from nested_category where left > 7 and left < 8 order by left asc,
which will bring no results.
For row number 1 the result however will bring the entire tree.
I have no php script for autocreating those columns on this computer, but there are plenty around. Im afraid they are also recursive.
You my find lots of info around searching for "nested set model", like this or theorical exaplanations of the model like this one
AND THIS IS A WAY DUPLICATED QUESTION (i can not put it as duplicated)
Some other answers:
You should reread the forum rules before posting, look for already asked questions.
Hope it helps.