0

I have a table with three columns: id, ref and catName. Every row contains a category which can be a sub category; if so than the ref column references to the id of the main category. Off course this method makes sure you can create numerous sub categories.

Now I want to make a url for every category containing of the catName's of all its parents.

private function getCatUrl($cat, $ur = array()){
       $sql = "SELECT * FROM shop_cat WHERE id = :id LIMIT 1";
       $st = $this->db->prepare($sql);
       $st->bindParam('id', $cat, PDO::PARAM_INT);
       $st->execute();

       $rij = $st->Fetch();
       $ur[] = urlencode($rij['naam']);

       if($rij['ref'] == 0){
           //Done, I've reached the top parent;
           return implode('/',$ur);

       }else{
           //there is a parent/reference above this level
           //getting there
           $this->getCatUrl($rij['ref'], $ur);

       }

   }

Somehow this only produces a $ur for the top parent and not for the childs. What am I doing wrong?

Sample of the database:

id  ref catName
1   0   GroundFloor
4   1   Portal
5   1   Stairs

2   0   FirstFloor
6   2   DiningArea
12  6   Chair
7   2   Toilet   
9   2   SittingRoom
10  9   Couch
11  9   Dresser

3   0   Roof
8   3   LoungeChair
stUrb
  • 6,612
  • 8
  • 43
  • 71
  • Can you include an example of your data from your DB. And an example of how you are calling this function (ie what params) – Manse Mar 05 '12 at 13:55

2 Answers2

0

The error is that you do not make sure that when the recursion stops, the results "bubble up" the call stack until finally the first invocation of the function returns to the caller. In code:

return $this->getCatUrl($rij['ref'], $ur); // add the return!
Jon
  • 428,835
  • 81
  • 738
  • 806
0

You are doing it wrong.

I would recommend for you to look into Closure Tables [1] [2] [3], and also read the SQL Antipatterns book ( it covers the trees in second chapter).

Community
  • 1
  • 1
tereško
  • 58,060
  • 25
  • 98
  • 150