PHP Syntax (Toggle Plain Text)

1. function GetDownline($member_id,$direction)
2. {
3. $getdownlinesql = @mysql_fetch_assoc(@mysql_query('select memberid,placementid,position from `yourrelationaltable` where placementid="'.$member_id.'" and position="'.$direction.'"'));
4. $getdownline = $getdownlinesql;
5. return $getdownline;
6. }
7. then simply call it with:
8. $firstleft = GetDownline('headmemberidhere','Left'); //for first left
9. $firstright = GetDownline('headmemberidhere','Right'); //for first right
10. echo $firstleft;
11. echo $firstright;

Hi Atli.
Could u Tell me That How I Can Store the Tree Level in Array.
For Example the 2,3,4,5 is First Level Node then i want to store these value in one array called $firstlevel
and another 6,7,8,9,10 is second level node of Parent Level then i want to store it in one array called $secondlevel
for Payment Devidation for MLM Business.

or If u Have any other Payment Devidation Solution then Please Tell me.

function GetChildDownline($member_id)     { 
    $getchilddownlinesql = @mysql_query('select memid,placementid,position from `yourtablehere` where placementid="'.$member_id.'" ORDER BY position'); 
    while($childdownline = mysql_fetch_array($getchilddownlinesql)){
        $childdownlinecode = $childdownline['memid'];
        $direction = $childdownline['position'];
        if($direction=='L'){
            if($childdownlinecode){ 
                //this is where you play with your html layout
                echo $childdownlinecode.'<br>';  
                //GetNextDownlines($childdownlinecode,'L'); //error 
                GetChildDownline($childdownlinecode);
            }
        } 
        if($direction=='R'){
            if($childdownlinecode){ 
                //this is where you play with your html layout
                echo $childdownlinecode.'<br>';  
                //GetNextDownlines($childdownlinecode,'R');//error  
                GetChildDownline($childdownlinecode);                       
            }
        }
    }
}

I am a student and i need this codes/script too. Can you please explain me step by step so that i will learn and complete my project ?

Hi,
I use code to display binary tree from database. It displaying values, but not drawing lines. I am using javascript code also

Please help me.
Replay please.

Murty

Hi Atli.
Could u Tell me That How I Can Store the Tree Level in Array.
For Example the 2,3,4,5 is First Level Node then i want to store these value in one array called $firstlevel
and another 6,7,8,9,10 is second level node of Parent Level then i want to store it in one array called $secondlevel
for Payment Devidation for MLM Business.

or If u Have any other Payment Devidation Solution then Please Tell me.

Hey. Sorry about the delay. (Been busy.)

You could add a public variable to the TreeView PHP class, to use as a container for this information, and have the TreeView::fetchTree method populate it as it reads the data from the database.

In my previous code, if you just added a public $levels at the top of the class, you could modify the TreeView::fetchTree method like so:

/**
 * A recursive function that fetches a tree-structure from a database into an array.
 * @global <mysqli> $dbLink A open MySQLI connection.
 * @param <array> $parentArray The pass-by-reference array to contain the results.
 * @param <number> $parentID The ID the current recursion uses as a root.
 * @param <number> $depth The current depth of the recursion.
 */
private function fetchTree(&$parentArray, $parentID=null, $depth=0)
{
    global $dbLink;

    // Create the query
    if($parentID == null) {
        $parentID = 0;
    }
    $sql = "SELECT `id` FROM `{$this->tblName}` WHERE `parentID`= ". intval($parentID);

    // Execute the query and go through the results.
    $result = $dbLink->query($sql);
    if($result)
    {
        while($row = $result->fetch_assoc())
        {
            // Add the ID to the levels array, at the current depth.
            $this->levels[$depth][] = $row['id'];

            // Create a child array for the current ID
            $currentID = $row['id'];
            $parentArray[$currentID] = array();

            // Print all children of the current ID
            $this->fetchTree($parentArray[$currentID], $currentID, $depth+1);
        }
        $result->close();
    }
    else {
        die("Failed to execute query! ($level / $parentID)");
    }
}

That way, your array would list all IDs at a given depth. You could display it like:

<div style="clear: both;">
        <pre><?php print_r($treeView->levels); ?></pre>
    </div>
</body>

Which might print something like:

(
    [0] => Array
        (
            [0] => 1
        )

    [1] => Array
        (
            [0] => 2
            [1] => 3
            [2] => 4
            [3] => 16
        )

    [2] => Array
        (
            [0] => 5
            [1] => 7
            [2] => 17
            [3] => 6
            [4] => 15
            [5] => 19
            [6] => 9
        )
)

Hope that's what your after.

I am a student and i need this codes/script too. Can you please explain me step by step so that i will learn and complete my project ?

Hey.
Are you referring to the code hemgoyal was talking about?

Hi,
I use code to display binary tree from database. It displaying values, but not drawing lines. I am using javascript code also

Please help me.
Replay please.

Murty

Hi.

Can you give us a little more details about your problem?
There is very little I can do to help without any error messages and/or the ability to see the code.

Hey.
Are you referring to the code hemgoyal was talking about?

yes, i could understand some but not all. please help me.

yes, i could understand some but not all. please help me.

Could you point out which parts you need help with?
It would take me a long time to explain the whole thing :)

Could you point out which parts you need help with?
It would take me a long time to explain the whole thing :)

The tree comes for the member in the root. how do i show tree for a particular member starting from himself. and how do i set rewards/achievement on completion of levels ? And i have seen some good graphics and boxes properly wrapped around the member name and id in the tree on some websites, how do i do that ?

can you please guide me building a complete mlm site or do you know any tutorials on building mlm sites with samples/examples ?

can you please guide me building a complete mlm site or do you know any tutorials on building mlm sites with samples/examples ?

I'm afraid I had not so much as heard of MLM sites, until I read the term in this thread. It's some sort of pyramid business schema, right? (I haven't exactly spent much time studying business tactics :$)

In any case, I don't think I will be of much help in building a complete MLM application. That would require a greater understanding of the subject than I have, or which I am able to learn right now. (I got a few projects of my own that keep me pretty busy :yawn:)

The tree comes for the member in the root. how do i show tree for a particular member starting from himself.

The second parameter of my TreeView::fetchTree method accepts a parentID, which would be used as the root of the resulting tree.
If you want the tree to be displayed from a specific ID, you would only have to modify the class so that you could supply the ID to the TreeView::createTree method, from within which you could forward it into the TreeView::fetchTree method.

and how do i set rewards/achievement on completion of levels ?

That I can't really tell you, as I have no idea of how those parts of your applications work, or even how you mean them to work. My examples in this thread are only focused on displaying a tree structure, not on the business-logic of the application that creates/manipulates the data for the tree.

And i have seen some good graphics and boxes properly wrapped around the member name and id in the tree on some websites, how do i do that ?

You would have to create the HTML/CSS you want displayed, and then modify the PHP and JavaScript code to output that HTML/CSS. The code I posted was just an example; something to get you started.
Everything you need to create whatever output you need is there. You just need to modify the basic output I used into whatever you need it to be. Again, this is not something I can detail for you step-by-step, because the modifications would be specific to your design, which I don't have.

I'm afraid I had not so much as heard of MLM sites, until I read the term in this thread. It's some sort of pyramid business schema, right? .............

Thanks a lot. I'll work on my project with all your hints/tips and will seek help too from you further.

Thanx Atli for Your Help.
From Your Help my work is too Easy.
Now I Can do Calculation of Payment for Each Member and Level after Storing the Data in Level Array.

Thanx Again.
and also i am Send fully designed code to bobbymoir.
if he couldn't understand that we don't do nothing.

Thanx Atli for Your Help.
From Your Help my work is too Easy.
Now I Can do Calculation of Payment for Each Member and Level after Storing the Data in Level Array.

Thanx Again.
and also i am Send fully designed code to bobbymoir.
if he couldn't understand that we don't do nothing.

Thank you Hemgoyal. Please send me the codes including Calculation of Payment for each members and levels. Thanks a lot.

Hello Sir,
Please tell How to call JavaScript start drawing the lines.

Please replay as soon as possible.
Murty

Hello Sir,
Please tell How to call JavaScript start drawing the lines.

Please replay as soon as possible.
Murty

Hey.

The code in my previous post (#24) is a working example. The JavaScript in the index.php file, starting on line #8, triggers the drawing of the lines.

<script type="text/javascript">
    // Have the TreeView.drawAll method executed as soon as the DOM is ready.
    $(document).ready(function(){ 
        TreeView.drawAll();
    });
</script>

Hello Sir,
Please tell How to call JavaScript start drawing the lines.

Please replay as soon as possible.
Murty

hay murty,
why not u read the whole forum that will be created by me and answered by atli. in this forum there are all things explained very well.

<?php
include("../includes/config.php"); 
//my database connection is set in my config, otherwise, just create your own db connect
$defaultmcode = 'yourdefaultidhere';
if($_GET['topmcode']){
$topmcode = trim($_GET['topmcode']);
}else{
$topmcode = $defaultmcode;
}
$topmcode = ltrim($topmcode);
$topmcode = rtrim($topmcode);
$topmcode = strtoupper($topmcode);
//my memberid are alphanumerics and all caps so I had to conver all to upper case, else, comment the above strtoupper call

//get Downline of a Member, this function is needed so that you can simply call left or right of the memberid you are looking for
		function GetDownline($member_id,$direction) 
		{ 
				$getdownlinesql = @mysql_fetch_assoc(@mysql_query('select memid,placementid,position from `yourtablehere` where placementid="'.$member_id.'" and  position="'.$direction.'"'));
				$getdownline = $getdownlinesql['memid'];
				return $getdownline; 
		}

//get the child of the member, this section will look for left or right of a member, once found, it will call GetNextDownlines() function to assign new memberid variables for left or right
    function GetChildDownline($member_id) 
    { 
				$getchilddownlinesql = @mysql_query('select memid,placementid,position from `yourtablehere` where placementid="'.$member_id.'" ORDER BY position');
				while($childdownline = mysql_fetch_array($getchilddownlinesql)){
						$childdownlinecode = $childdownline['memid'];
						$direction = $childdownline['position'];
						if($direction=='L'){
							if($childdownlinecode){
								//this is where you play with your html layout
								echo $childdownlinecode.'<br>';
								GetNextDownlines($childdownlinecode,'L');
							}
						}
						
							if($direction=='R'){
								if($childdownlinecode){
									//this is where you play with your html layout
									echo $childdownlinecode.'<br>';
									GetNextDownlines($childdownlinecode,'R');
							}
						}
				 }
    }

//recursive function to call the functions and start all over again, this is where you can get the newly assigned memberid, call the GetChildDownline() that gets the left or right, then recycle all codes
    function GetNextDownlines($member_id,$direction) 
    {
			if($direction=='L'){
					$topleft = GetDownline($member_id,'L');
						if($topleft){
								//this is where you play with your html layout
						echo $topleft.'<br>';
						}
							$getleftdownlinesql = @mysql_query('select memid,placementid,position from `yourtablehere` where placementid="'.$topleft.'" ORDER BY position');
							while($getleftdownline = mysql_fetch_array($getleftdownlinesql)){
							$leftdownline = $getleftdownline['memid'];
							$leftdirection = $getleftdownline['position'];
							
							if($leftdirection=='L'){
									if($leftdownline){
								//this is where you play with your html layout
										echo $leftdownline.'<br>';
										GetChildDownline($leftdownline);
									}
							  }
							
							if($leftdirection=='R'){
									if($leftdownline){
								//this is where you play with your html layout
									echo $leftdownline.'<br>';
									 GetChildDownline($leftdownline);
									 }
							   }
							 }
			}
			
			
			if($direction=='R'){
						$topright = GetDownline($member_id,'R');
						if($topright){
						echo $topright.'<br>';
						}
						$getrightdownlinesql = @mysql_query('select memid,placementid,position from `yourtablehere` where placementid="'.$topright.'" ORDER BY position');
						while($getrightdownline = @mysql_fetch_array($getrightdownlinesql)){
									$rightdownline = $getrightdownline['memid'];
									$rightdirection = $getrightdownline['position'];
									
									if($rightdirection=='L'){
											if($rightdownline){
								//this is where you play with your html layout
											echo $rightdownline.'<br>';
											GetChildDownline($rightdownline);
											}
									}
									
									if($rightdirection=='R'){
											if($rightdownline){
								//this is where you play with your html layout
											echo $rightdownline.'<br>';
											GetChildDownline($rightdownline);
											}
									}
						
							}
				}
}

?>
<html>
	<head>
	<title>Genealogy</title>
	<meta http-equiv=Content-Type content="text/html; charset=utf-8">
	<meta http-equiv=content-language content=en>
	<link href="styles.css" type=text/css rel=stylesheet>
	</head>
<body>
<table cellpadding="0" cellspacing="0" width="100%" border="0" class="noborder">
 <tr>
	<td>
<?php
echo $topmcode.'<br>';
GetNextDownlines($topmcode,'L');
GetNextDownlines($topmcode,'R');
?>

	</td>
 </tr>
</table>
</body>
</html>

Hi i using your above code but it showing error . I am new to tree.
I am not identify the error. Please help me.

Error: mysql_fetch_array(): supplied argument is not a valid MySQL result resource.

Please replay .
Raju

Hay murty14,
Why not you use the code that is posted by atli in #24 reply.
This is best and fully working for me.

Thank You.

commented: this is for multilevel. if we think from position left or right then this code not working +0

Hi want to create a binary tree using table registration having fields id, parent_id, user_name.
id Parent_id user_name
1 0 SF8011049
2 1 SF6542248
3 1 SF2998128
4 2 SF2518457
5 2 SF7055311
6 3 SF0207585
7 3 SF6258770

Please tell how to create binary using this table. Please any body help me to display binary tree having username in the tree structure. Please help me.

Please quick replay
Murty

Hi want to create a binary tree using table registration having fields id, parent_id, user_name.
id Parent_id user_name
1 0 SF8011049
2 1 SF6542248
3 1 SF2998128
4 2 SF2518457
5 2 SF7055311
6 3 SF0207585
7 3 SF6258770

Please tell how to create binary using this table. Please any body help me to display binary tree having username in the tree structure. Please help me.

Please quick replay
Murty

Hey. (... again?)

I have already posted a complete, working code example that uses an extremely similar table as it's data-source. You wold only have to alter the SQL queries to make it compatible.

I'm not going to re-post it here again, just to make it fit your (extremely similar) database. I suggest you use that code as a base and try to do this yourself.

If you run into problems, post them here and we will try to help.
If you do, please include the info we need to help you. (A description of the problem, error messages, data samples, etc...)

To reiterate: post #24, page #2, this thread.

The problem is that the code relies on your browser to correctly align the <div> elements. When the tree is wider then the browser window, the browser automatically re-arranges the <div> elements to fit the window size.

What you need to do to get around this is to create a container around the tree - a <div> element - and manually set it's width to something large enough to contain the entire width of the tree. This will add a horizontal scroll-bar to the browser window, allowing you to scroll sideways to see the parts of the tree that will not fit.

To that end, try altering the PHP TreeView::createTree method to include this container div in the tree output.
Starting at line #74:

// Set up the CSS styles, and create the container DIV.
            $divID = "TreeView_ContainerDiv_" . $GLOBALS['TreeView_DivID'];
            $output = <<<HTML
<style type="text/css">
    div#{$divID}     { margin: 0; padding: 0; text-align: center; }
    div#{$divID}_Inner { width: 5000px; }
    div#{$divID} div { margin: 0; padding: 0 10px; float: left; {$this->bgColor}}
    div#{$divID} p   { margin: 0; padding: 0; margin-bottom: 10px; }
</style>
<div id="{$divID}">
    <div id="{$divID}_Inner">
HTML;

            // Add the DIV hierachy.
            $this->buildHtml($treeData, $output);

            // Add the JavaScript call to start drawing the lines
            $rootID = array_keys($treeData);
            $rootID = $rootID[0];
            $output .= <<<HTML
    </div>
    <script type="text/javascript">
        TreeView.addTree('Tree{$GLOBALS['TreeView_DivID']}_{$rootID}');
    </script>
</div>
HTML;

This will set the maximum with of the tree to 5000px, which should be large enough for a pretty large tree.

sir this is a great code & it's helped me alot, how to print one more field called name & how to fill non-active left & right nodes? please help me.

Hi,

You can try to approach this in different ways, however, you will need to see how you would layout your page too. Based on my experience, the layout you were looking at will grow wider so you will need to limit how much you can show per page.

I will try to give you 2 approaches I can think of that might work for you.

First, limit your display up to 15 IDs only, this will allow you to put as much details as you need per ID, please refer to the illustration taken from my genealogy system:

http://i34.tinypic.com/j9x63b.jpg

This method will allow your database to breathe from over-processing because of recursive calls.
What I did with this was just layout an html page and used a function call to get left and right till you fill all 15 slots. Here is the php code I use:

function GetDownline($member_id,$direction) 
    { 
$getdownlinesql = @mysql_fetch_assoc(@mysql_query('select memberid,placementid,position from `yourrelationaltable` where placementid="'.$member_id.'" and  position="'.$direction.'"'));
$getdownline = $getdownlinesql['memberid'];
return $getdownline; 
    }

then simply call it with:
$firstleft = GetDownline('headmemberidhere','Left'); //for first left
$firstright = GetDownline('headmemberidhere','Right'); //for first right
echo $firstleft;
echo $firstright;

Now for the next left or right

$secondleftofleft = GetDownline($firstleft,'Left'); //for second left of first left
$secondrightofleft = GetDownline($firstleft,'Right'); //for second right of first left

echo $secondleftofleft;
echo $secondrightofleft;

$secondleftofright = GetDownline($firstright,'Left'); for second left of first right
$secondrightofright = GetDownline($firstright,'Right'); for second right of first right

echo $secondleftofright;
echo $secondrightofright;

..And so on, now you can build your 15 tree line on a page, to give the effect of going downline, you can make all of the buttons clickable carrying their own member id's so it makes it the top of the tree, just to a GET or POST method to assign a new value for headmemberidhere that serves as your head of the tree.

Note:
This is not my exact code and is for illustration purposed only, but the code will work as is.

That is the simplest method to have a nice layout of the binary tree.

The next one is the full recursive method similar to Atli's post.

However, this approach is not recommended if you are on a shared server or have a large database like I have.

The full recursive method I did was a bit complicated to get the effect due to the nature of my database structure. I actually had an existing database to work on so I had difficulties adapting or creating the proper code since I had to adapt to the database instead of me creating the perfect code that will do a simple recursive structure.

Below is the method I used to make recursion work from top to bottom of the tree in full view.

I did three function calls to so that each set will call different codes at the same time in recursion, I am not sure how to do this easily too because of the existing database structure.

Here is an illustrative php code for you:

<?php
include("../includes/config.php"); 
//my database connection is set in my config, otherwise, just create your own db connect
$defaultmcode = 'yourdefaultidhere';
if($_GET['topmcode']){
$topmcode = trim($_GET['topmcode']);
}else{
$topmcode = $defaultmcode;
}
$topmcode = ltrim($topmcode);
$topmcode = rtrim($topmcode);
$topmcode = strtoupper($topmcode);
//my memberid are alphanumerics and all caps so I had to conver all to upper case, else, comment the above strtoupper call

//get Downline of a Member, this function is needed so that you can simply call left or right of the memberid you are looking for
		function GetDownline($member_id,$direction) 
		{ 
				$getdownlinesql = @mysql_fetch_assoc(@mysql_query('select memid,placementid,position from `yourtablehere` where placementid="'.$member_id.'" and  position="'.$direction.'"'));
				$getdownline = $getdownlinesql['memid'];
				return $getdownline; 
		}

//get the child of the member, this section will look for left or right of a member, once found, it will call GetNextDownlines() function to assign new memberid variables for left or right
    function GetChildDownline($member_id) 
    { 
				$getchilddownlinesql = @mysql_query('select memid,placementid,position from `yourtablehere` where placementid="'.$member_id.'" ORDER BY position');
				while($childdownline = mysql_fetch_array($getchilddownlinesql)){
						$childdownlinecode = $childdownline['memid'];
						$direction = $childdownline['position'];
						if($direction=='L'){
							if($childdownlinecode){
								//this is where you play with your html layout
								echo $childdownlinecode.'<br>';
								GetNextDownlines($childdownlinecode,'L');
							}
						}
						
							if($direction=='R'){
								if($childdownlinecode){
									//this is where you play with your html layout
									echo $childdownlinecode.'<br>';
									GetNextDownlines($childdownlinecode,'R');
							}
						}
				 }
    }

//recursive function to call the functions and start all over again, this is where you can get the newly assigned memberid, call the GetChildDownline() that gets the left or right, then recycle all codes
    function GetNextDownlines($member_id,$direction) 
    {
			if($direction=='L'){
					$topleft = GetDownline($member_id,'L');
						if($topleft){
								//this is where you play with your html layout
						echo $topleft.'<br>';
						}
							$getleftdownlinesql = @mysql_query('select memid,placementid,position from `yourtablehere` where placementid="'.$topleft.'" ORDER BY position');
							while($getleftdownline = mysql_fetch_array($getleftdownlinesql)){
							$leftdownline = $getleftdownline['memid'];
							$leftdirection = $getleftdownline['position'];
							
							if($leftdirection=='L'){
									if($leftdownline){
								//this is where you play with your html layout
										echo $leftdownline.'<br>';
										GetChildDownline($leftdownline);
									}
							  }
							
							if($leftdirection=='R'){
									if($leftdownline){
								//this is where you play with your html layout
									echo $leftdownline.'<br>';
									 GetChildDownline($leftdownline);
									 }
							   }
							 }
			}
			
			
			if($direction=='R'){
						$topright = GetDownline($member_id,'R');
						if($topright){
						echo $topright.'<br>';
						}
						$getrightdownlinesql = @mysql_query('select memid,placementid,position from `yourtablehere` where placementid="'.$topright.'" ORDER BY position');
						while($getrightdownline = @mysql_fetch_array($getrightdownlinesql)){
									$rightdownline = $getrightdownline['memid'];
									$rightdirection = $getrightdownline['position'];
									
									if($rightdirection=='L'){
											if($rightdownline){
								//this is where you play with your html layout
											echo $rightdownline.'<br>';
											GetChildDownline($rightdownline);
											}
									}
									
									if($rightdirection=='R'){
											if($rightdownline){
								//this is where you play with your html layout
											echo $rightdownline.'<br>';
											GetChildDownline($rightdownline);
											}
									}
						
							}
				}
}

?>
<html>
	<head>
	<title>Genealogy</title>
	<meta http-equiv=Content-Type content="text/html; charset=utf-8">
	<meta http-equiv=content-language content=en>
	<link href="styles.css" type=text/css rel=stylesheet>
	</head>
<body>
<table cellpadding="0" cellspacing="0" width="100%" border="0" class="noborder">
 <tr>
	<td>
<?php
echo $topmcode.'<br>';
GetNextDownlines($topmcode,'L');
GetNextDownlines($topmcode,'R');
?>

	</td>
 </tr>
</table>
</body>
</html>

This is not the full code, but it gives you insights on how to do full recursive view on your data structure. Also, this is a product of 3:30 AM with no sleep yet so it maybe sloppy and redundant... hehe

If you can make it thinner or smaller it would be better, or if there is a real way to recycles codes without my redundancies....

I hope this helps

Thanks for u r code and i need the css file which u included in the program im getting every thing but unable to set the proper design

commented: hello sir, you got css file of above code?? +0

dude why not u use the code that is posted by atli in #24.
please try it. it's predesigned and well formated with css.

hi please help me guys.
i have a table "child" with
id_no child_name child_loc parent_id
1 xyz left 0
2 abc right 1
3 nop right 2
4 lmn left 1
5 ijk right 3
it is a example where id_no is a primary key.
i wand to make a dynamic table in PHP which can show parent and his 2 child....plzzz help its urgent.

commented: hello sir, have you done your work? +0

real the complete forum carefully..
you may find your answer posted by atli.

hemgoyal can u plz tell me the structure of data base????

real the complete forum carefully..
you may find your answer posted by atli.

can u plz tell me the structure of data base and how to impliment this code ???
i m new to PHP !

Thanks for that piece of code, it will be useful for a project I'm running right now in multinivel industry...

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.