How can I recursively obtain the “parent ID” of rows in this MySQL table?

后端 未结 3 1265
天命终不由人
天命终不由人 2020-12-03 20:38

My database looks like (pligg cms, sample data)

id  catID parentID   catName
1    1      0        location
2    2      0        color
3    3      1        US         


        
3条回答
  •  心在旅途
    2020-12-03 20:51

    Based on @GWW answer

    function getLocationArray($start){
        $link=dbConnect();//a function returning the link with your db
        $stack = array();
        $parent = $start;
        while($parent != 0){
            $query='SELECT catName,parentID from myTable where catId='.$parent;
            $result = mysql_query($query,$link);
            while($row = mysql_fetch_assoc($result)){
                $parent=$row['parentID'];
                $name=$row['catName'];
                $stack[] = $name;
                /*foreach($row as $cname => $cvalue){
                }*/
            }
        }
        $stack = array_reverse($stack);
        return $stack;
    }
    var_dump($stack);
    

提交回复
热议问题