hello friends , i need a help to create a binary tree using PHP and mysql. Friends i able to create a tree which is start form parentID with 0 successfully , but when i try to create tree with parent ID=1 , this time i just getting all the child member tree but Root Node OR Parent Node is not getting . So i want to show parent node also ....please help me...

my Index file where i m displaying the tree
[CODE]
<!DOCTYPE html>
<html>
    <head>
        <title>Tree-view Test</title>
            <meta http-equiv="Content-Type" content="text/html; charset=utf8">
                <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
                <script type="text/javascript" src="TreeView.js"></script>
                <script type="text/javascript">
                    $(document).ready(function(){
                        TreeView.drawAll();
                    });
                </script>
    </head>
    <body bgcolor="red">
    <table width="100%"><tr><td><center>
    <?php
    ini_set('display_errors', true);
    error_reporting(E_ALL);
    include("TreeView.inc");
    $dbLink = new mysqli("localhost", "root", "", "tree");
    $treeView = new TreeView($dbLink);
    $treeView->printTree('treeview');
     $dbLink->close();
    ?><!-- below code is for collecting the memmber id in arrary by level --><!--<div style="clear: both;">
            <pre><?php print_r($treeView->levels); ?></pre>
        </div>
--></center></td></Tr></table>
    </body>
</html>
[/CODE]
treeview.inc file , logic of php for creating the tree
[CODE]<?php
class TreeView
{
private $bgColor ="white";
private $dbLink;
private $tblName;
public $levels;
public $TreeView_DivID=0;
public function __construct(mysqli $dbLink)
{
if($dbLink != null && $dbLink->connect_errno == 0)
{
$this->dbLink = $dbLink;
if(!isset($GLOBALS["TreeView_DivID"]))
{
$GLOBALS["TreeView_DivID"]=0;
}
}
else
{
throw new Exception("The mysqli object provided is invalid.");
}
}
public function createTree($tblName)
{
if(!isset($tblName) || empty($tblName))
{
throw new Exception("Failed to create the tree. Table or database information is invalid");
}
else
{
$this->tblName = $tblName;
$treeData = array();
$output = "";
$this->fetchTree($treeData);
$divID = "TreeView_ContainerDiv_" . $GLOBALS["TreeView_DivID"];
$output = <<<HTML
<style type="text/css">
div#{$divID} { margin: 0; padding: 0; text-align: center; color:white;}
div#{$divID} div { margin: 0; padding: 0 5px; float: left;}
div#{$divID} p {  margin: 0; padding: 0; margin-bottom: 10px;color:white;background-image:url('abc.jpg'); height:50px;width:50px; text-align: center}
</style>
<div id="{$divID}" align="center">
<div id="{$divID}_Inner" align="center">
HTML;
$this->buildHtml($treeData, $output);
$rootID = array_keys($treeData);
$rootID = $rootID[0];
$output .= <<<HTML
</div>
<script type="text/javascript">
TreeView.addTree('Tree{$GLOBALS['TreeView_DivID']}_{$rootID}');
</script>
</div>
HTML;
$GLOBALS["TreeView_DivID"]++;   
return $output;
}
}
public function printTree($tblName)
{
echo $this->createTree($tblName);
}
private function fetchTree(&$parentArray, $parentID=null, $depth=0)
{
global $dbLink;
if($parentID == null)
{
$parentID = 1;
}
$sql = "SELECT `id` FROM `{$this->tblName}` WHERE `parentID`= ". intval($parentID);
$result = $dbLink->query($sql);
if($result)
{
while($row = mysqli_fetch_assoc($result))
{
$this->levels[$depth][]= $row['id'];
$currentID = $row['id'];
$parentArray[$currentID] = array();
$this->fetchTree($parentArray[$currentID], $currentID, $depth+1);
}
$result->close();
}
else
{
die("Failed to execute query! ($level / $parentID)");
}
}
private function buildHtml($data, &$output)
{
foreach($data as $_id => $_children)
{
$output .= "<div style='background-color:white;' id=\"Tree{$GLOBALS["TreeView_DivID"]}_{$_id}\"><p>{$_id}</p>";
$this->buildHtml($_children, $output);
$output .= "</div>";
}
}
}
?>[/CODE]

Java script file for drawing line between node

[CODE]    /**
     * Handles drawing lines between the tree structures generated by PHP.
     */
    var TreeView =
    {
    /** Constants (sort of) **/
    LINE_MARGIN : 20, // px
    BORDER_STYLE : "solid 2px red",

    /** A list of root elements to draw when the window is loaded. */
    trees : [],

    /**
      * Adds a tree to the list of trees to be drawn.
      * @param rootID The ID of the root element of the tree.
      */
    addTree : function(rootID)
    {
    this.trees.push(rootID);
    },

    /**
      * Loops through all the trees and executes the drawing function for each of them.
      */
    drawAll : function()
    {
    for(var x = 0; x < this.trees.length; x++)
    {
    var root = $("#" + this.trees[x]);
    if(root.length > 0)
    {
    this.drawTree(root);
    }
    }
    },

    /**
      * Recursively draws all lines between all root-child elements in the given tree.
      * @param root The root element of the tree to be drawn.
      */
    drawTree : function(root)
    {
    root = $(root);
    if(root.length > 0)
    {
    var children = root.children('div');
    for(var i = 0; i < children.length; i++)
    {
    this.drawLine(root, children[i]);
    this.drawTree(children[i]);
    }
    }
    },

    /**
      * Draws a line between the two passed elements.
      * Uses an absolutely positioned <div> element with the borders as the lines.
      * @param elem1 The first element
      * @param elem2 The second element
      */
    drawLine : function(elem1, elem2)
    {
    // Use the <p> element as the base. Otherwise the height() call on the
    // <div> will return the entire hight of the tree, including the children.
    elem1 = $(elem1).find("p").eq(0);
    elem2 = $(elem2).find("p").eq(0);

    var e1_pos = $(elem1).position();
    var e2_pos = $(elem2).position();
    var borders = { top:true, left:true, right:false, bottom:false };

    // Move the position to the center of the element
    e1_pos.left += ($(elem1).width() / 2);
    e1_pos.top += ($(elem1).height() / 2);
    e2_pos.left += ($(elem2).width() / 2);
    e2_pos.top += ($(elem2).height() / 2);

    // Position if they are horizontally aligned.
    if(e1_pos.left == e2_pos.left)
    {
    borders.top = false;
    if(e1_pos.top < e2_pos.top)
    {
    e1_pos.top += ($(elem1).height() / 2);
    e2_pos.top -= ($(elem2).height() / 2);
    }
    else
    {
    e1_pos.top -= ($(elem1).height() / 2);
    e2_pos.top += ($(elem2).height() / 2);
    }
    }

    // Position if they are verticaly aligned.
    else if(e1_pos.top == e2_pos.top)
    {
    borders.left = false;
    e1_pos.top += ($(elem1).height() / 2);
    e2_pos.top += ($(elem2).height() / 2);
    if(e1_pos.left < e2_pos.left)
    {
    e1_pos.left += $(elem1).width();
    }
    else
    {
    e2_pos.top += $(elem2).height();
    }
    }

    // Position if the elements are not aligned.
    else
    {
    if(e1_pos.left < e2_pos.left)
    {
    borders.right = true;
    borders.left = false;
    }

    if(e1_pos.top > e2_pos.top)
    {
    borders.bottom = true;
    borders.top = false;
    }
    }

    // Calculate the overlay position and size
    var over_position = {
    left:(e1_pos.left < e2_pos.left ? e1_pos.left : e2_pos.left),
    top:(e1_pos.top < e2_pos.top ? e1_pos.top : e2_pos.top)
    };
    var over_size = {
    width:Math.abs(e1_pos.left - e2_pos.left),
    height:Math.abs(e1_pos.top - e2_pos.top)
    }

    // Create the overlay div
    var raw_overlay = document.createElement('div');
    var overlay = $(raw_overlay);

    // Add the borders, and create a margin for the lines so they are not
    // drawn "into" the numbers.
    if(borders.top) {
    overlay.css('border-top', this.BORDER_STYLE);
    over_size.height -= this.LINE_MARGIN;
    }
    if(borders.bottom) {
    overlay.css('border-bottom', this.BORDER_STYLE);
    over_position.top += this.LINE_MARGIN;
    over_size.height -= this.LINE_MARGIN;
    }
    if(borders.left) {
    overlay.css('border-left', this.BORDER_STYLE);
    over_size.width -= this.LINE_MARGIN;
    }
    if(borders.right) {
    overlay.css('border-right', this.BORDER_STYLE);
    over_position.left += this.LINE_MARGIN;
    over_size.width -= this.LINE_MARGIN;
    }

    overlay.css('position', 'absolute');
    overlay.css('top', over_position.top);
    overlay.css('left', over_position.left);
    overlay.css('width', over_size.width);
    overlay.css('height', over_size.height);

    document.body.appendChild(overlay.get(0));
    }
    }[/CODE]

Please help meeeeeeeeeeeeeeee

Please help meeeeeeeeeeeeeeee

hi peterpa,
did you get the answer of this problem?

Hey I understand your problem but I don’t identify how to solve it. In my suggestion you may solve this problem along with any professional mlm company. That’s why I said because I created mlm website throughout arm mlm software.

help me please how to create binary tree structure

Well I'm not to sure how many levels do you have and also I didn't read your code that much. In my case there are 5 levels so what I did was first get the current user's ID then get how many children that user have, once I have that I then loop though each child to find out how many child each have which those are now grand childrens of the current user same thing again with the grand children loop through them to get their grand children which are this current users grand grand childrens and so on to level 5.

With that you can also get their details such as name, usernames, their total tree number and so on.

Can anybody tell me ,how to create binary tree in php and mysql and Genealogy and tree..please help me

@Suhasini. You can't hijack other people's posts, also you need to show us what you have done, where you stuck or having a problem. One thing you should know MLM systems are a bit complex depending on it function as well as its number of levels. Personally I've used the loops to loop through to find all the relenvent teams and their data, like names, IDs, account types, status, balances etc. If you want to take that approach, well I don't know in your case what you use as identifier of a user, I used unique ids which are generated and issued to a person on registration which is what that person issues to people to join under that person so that the system will know who introduced who.

1) Get the current use's Unique code.
NB: I have a transaction table where I keep track of every action is performed by any users (only the meningful and essential information). I have a column pin, and anotherone ref. pin is for new person introduced by ref.
2) Now get all the pin where ref = this current user's unique code.(These are level1 of this person who's currently logged in)
3) Now that you have the codes for your level 1 now loop for level 2 which is same as of getting level 1 but this time you use the for each statement because you may have more then 1 people on level1 so you need to get all of their levels.
4) Do the same to the end of your levels.

NB: you will have to reference the newely retrieved codes to be able to pull the correct data.

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.