0

Ok Guys I am seriously stuck with this. Despite reading a dozen solutions I cannot get it straight..

Here is my MySql table..uid stands for user id and parentid stands for the parent where the user belongs.

    id  parentid  uid
    1   0         1
    2   1         2
    3   1         3
    4   2         4
    5   2         5
    6   3         6
    7   3         7

Now this is what I did.

            $con = mysql_connect("localhost","rtest","123456");
            if (!$con)
             {
              die('Could not connect: ' . mysql_error());
             }
            else
             {
              mysql_select_db("rtest", $con);
              $sql="SELECT * FROM parentchild WHERE parentid=1";
              $results=mysql_query($sql);
              while($row = mysql_fetch_array($results))
             {
                $levelone[] = $row;
             }
            }
            mysql_close($con);
            foreach ($levelone as &$value) {
              echo $value[uid]."<br>";
            }  

Here I have childs of the 1st element. I am unable to figure out how to take the second array and get the further values and store them in more arrays. I also need to access individual arrays later and I cannot call the entire table in one array for security reasons. My logic is really weak here.

Please help and advice. Thanx a ton in advance..

thumber nirmal
  • 1,639
  • 3
  • 16
  • 27
DarthVader
  • 98
  • 8
  • http://dipesharea.wordpress.com/2011/06/03/n-level-category/ – Dipesh Parmar Mar 30 '13 at 06:54
  • Maybe a duplicate of ? http://stackoverflow.com/questions/607052/hierarchical-recursion-menu-with-php-mysql – bestprogrammerintheworld Mar 30 '13 at 07:01
  • 1
    What's the eventual data structure you're trying to create? – Barmar Mar 30 '13 at 07:26
  • off topic, but it's worth pointing out that the `mysql` functions are deprecated; if at all possible, you should switch to using the `mysqli` or `PDO` libraries instead (preferably PDO). – Spudley Mar 30 '13 at 08:02
  • @barmer i need to get a tree level structure but retail individual arrays for later use at each level. for example in the above code it gives out array for which the parent id is 1. i need that array then again iterate in that array and get 2 more arrays quering the database... – DarthVader Mar 30 '13 at 08:40

1 Answers1

0

You can get the list of parentids by

SELECT DISTINCT parentid FROM parentchild

Now you can simply loop over this list and get the correspoding childs

Tyranicangel
  • 189
  • 2
  • 16