| | |
Binary Tree Using PHP & MySQL
Please support our PHP advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
![]() |
I m working on a MLM project in which i have to store member automatically in binary tree form like
1 is root
2 is child of 1
3 is child of 1
Then 4 is child of 2
5 is child of 2
6 is child of 3
7 is child of 3
then 8 is child of 4
and so on ......
I Want to Create a Downline in above Structure. Please Help me.
can any body help me
1 is root
2 is child of 1
3 is child of 1
Then 4 is child of 2
5 is child of 2
6 is child of 3
7 is child of 3
then 8 is child of 4
and so on ......
I Want to Create a Downline in above Structure. Please Help me.
can any body help me
http://www.kuchamancity.com
Hem Web Solution..
Behind Every Successful Man, There is an Untold Pain in His Heart.
Hem Web Solution..
Behind Every Successful Man, There is an Untold Pain in His Heart.
0
#3 32 Days Ago
okay...
but how i can create downline from this database structure?
but how i can create downline from this database structure?
http://www.kuchamancity.com
Hem Web Solution..
Behind Every Successful Man, There is an Untold Pain in His Heart.
Hem Web Solution..
Behind Every Successful Man, There is an Untold Pain in His Heart.
0
#4 32 Days Ago
Hey.
You could do this using a recursive function.
For example, using a table like this:
You could do:
Which would give you:
Hope that helps.
You could do this using a recursive function.
For example, using a table like this:
text Syntax (Toggle Plain Text)
mysql> SELECT * FROM tree; +----+----------+ | id | parentID | +----+----------+ | 1 | NULL | | 2 | 1 | | 3 | 1 | | 4 | 1 | | 5 | 2 | | 6 | 3 | | 7 | 2 | | 8 | 5 | | 9 | 4 | +----+----------+
php Syntax (Toggle Plain Text)
<?php header("content-type: text/plain"); /** * A recursive function that prints a tree-structure. * @global <mysqli> $dbLink A open MySQLI connection. * @param <number> $level Used to determine how far from the root the current ID is. * @param <number> $parentID The ID the current recursion uses as a root. */ function printTree($level=0, $parentID=null) { global $dbLink; // Create the query $sql = "SELECT id FROM tree WHERE "; if($parentID == null) { $sql .= "parentID IS NULL"; } else { $sql .= "`parentID`=" . intval($parentID); } // Execute the query and go through the results. $result = $dbLink->query($sql); if($result) { while($row = $result->fetch_assoc()) { // Print the current ID; $currentID = $row['id']; for($i = 0; $i < $level; $i++) { echo " "; } echo $currentID . PHP_EOL; // Print all children of the current ID printTree($level+1, $currentID); } $result->close(); } else { die("Failed to execute query! ($level / $parentID)"); } } // Open a MySQLI connection and execute the function. $dbLink = new mysqli("host", "usr", "passwd", "dbName"); printTree(); $dbLink->close(); ?>
text Syntax (Toggle Plain Text)
1 2 5 8 7 3 6 4 9
Please do not ask for help in a PM. Use the forums.
And use [code] tags!
And use [code] tags!
0
#5 31 Days Ago
@above.
Thanx for Your Solution. Your Provide Solution is Most Helpful for me but i want to Create the Downline in Below Mention Structure:
Hope You are Understand.
Some Information:
Table Name is: admin_regdata
field: name, ID, Sponsor_ID, Address, Date_of_joining
Please Hep me.
Thanx for Your Solution. Your Provide Solution is Most Helpful for me but i want to Create the Downline in Below Mention Structure:
PHP Syntax (Toggle Plain Text)
Structure: ID(1) /\ ID(2) ID(3) /\ /\ ID(4) ID(5) ID(6) ID(7) Example: A /\ B C /\ /\ D E F G
Hope You are Understand.
Some Information:
Table Name is: admin_regdata
field: name, ID, Sponsor_ID, Address, Date_of_joining
Please Hep me.
http://www.kuchamancity.com
Hem Web Solution..
Behind Every Successful Man, There is an Untold Pain in His Heart.
Hem Web Solution..
Behind Every Successful Man, There is an Untold Pain in His Heart.
0
#6 30 Days Ago
anyone please help..
it's urgent..
it's urgent..
http://www.kuchamancity.com
Hem Web Solution..
Behind Every Successful Man, There is an Untold Pain in His Heart.
Hem Web Solution..
Behind Every Successful Man, There is an Untold Pain in His Heart.
•
•
Join Date: Oct 2009
Posts: 2
Reputation:
Solved Threads: 0
0
#7 28 Days Ago
Hi,
I am new to this forum and just wanted to share my thoughts on your issue.
I was on the same boat as you are so I know how hard it is. Let me explain how you can structure this.
my structure consists of 3 important fields, membercode, uplinecode and position
to create the binary, you first have to have a head, so add one on the database, then from there, you use that first member id as your upline code. Now that you have your upline code, you can now add 2 members to serve as your binary, membercode1 position left, membercode2 position right, both with same upline code, you now created your first downline... you can continue doing this to the next level... I will try to illustrate this as much as I can:
on my database, it will be
membercode sponsorcode position
code1 headcode Left
code2 headcode Right
So now headcode already have left and right, to continue,
membercode sponsorcode position
code1 headcode Left
code2 headcode Right
newcode1 code1 Left
newcode2 code1 Right
thirdcode1 newcode1 Left
thirdcode2 newcode1 Right
based on the illustration above, headcode will have 3 levels down on binary already.
The trick here is the upline code that is tagging on the membercode together with the position, since both sides are already filled, then you can simply try to validate and skip the member who already has left and right.
Hope it helps,
Paul
I am new to this forum and just wanted to share my thoughts on your issue.
I was on the same boat as you are so I know how hard it is. Let me explain how you can structure this.
my structure consists of 3 important fields, membercode, uplinecode and position
to create the binary, you first have to have a head, so add one on the database, then from there, you use that first member id as your upline code. Now that you have your upline code, you can now add 2 members to serve as your binary, membercode1 position left, membercode2 position right, both with same upline code, you now created your first downline... you can continue doing this to the next level... I will try to illustrate this as much as I can:
on my database, it will be
membercode sponsorcode position
code1 headcode Left
code2 headcode Right
So now headcode already have left and right, to continue,
membercode sponsorcode position
code1 headcode Left
code2 headcode Right
newcode1 code1 Left
newcode2 code1 Right
thirdcode1 newcode1 Left
thirdcode2 newcode1 Right
based on the illustration above, headcode will have 3 levels down on binary already.
PHP Syntax (Toggle Plain Text)
headcode / \ code1 code2 / \ newcode1 newcode2 / \ thirdcode1 thirdcode2
Hope it helps,
Paul
Last edited by wenzlerpaul; 28 Days Ago at 5:47 am.
0
#8 27 Days Ago
@above Thanx for Your Help.
I am Understand what u Want to Understanding me.
but Tell me The PHP Code that How Print the Above Illustration.
I am Understand that How to Store Binary Tree Data in Database.
any Help will be Appreciated.
Thank You.
I am Understand what u Want to Understanding me.
but Tell me The PHP Code that How Print the Above Illustration.
I am Understand that How to Store Binary Tree Data in Database.
any Help will be Appreciated.
Thank You.
http://www.kuchamancity.com
Hem Web Solution..
Behind Every Successful Man, There is an Untold Pain in His Heart.
Hem Web Solution..
Behind Every Successful Man, There is an Untold Pain in His Heart.
•
•
Join Date: Oct 2009
Posts: 2
Reputation:
Solved Threads: 0
1
#9 27 Days Ago
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:
Now for the next left or right
..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:
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
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:
PHP Syntax (Toggle Plain Text)
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;
PHP Syntax (Toggle Plain Text)
$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 Syntax (Toggle Plain Text)
<?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
Last edited by wenzlerpaul; 27 Days Ago at 12:41 pm.
0
#10 26 Days Ago
Hey.
Sorry it took me so long to respond. Been busy.
Anyhow, here is my take on this problem.
Positioning the IDs themselves can be done fairly easily with HTML, but the lines between parent-child IDs aren't as easily created.
I created this, which creates a HTML hierarchy of <div> elements, which positions the IDs with their parents. I over-commented the code, so I won't explain to much.
Which you could use like so:
This won't draw lines between the IDs, but it will position them nicely. I though about using JavaScript to draw the lines, but I'm way to tired for that at the moment xD
P.S.
Don't try this using Internet Explorer. It has a problem rendering CSS rules defined this decade, so the background colors won't show.
Sorry it took me so long to respond. Been busy.
Anyhow, here is my take on this problem.
Positioning the IDs themselves can be done fairly easily with HTML, but the lines between parent-child IDs aren't as easily created.
I created this, which creates a HTML hierarchy of <div> elements, which positions the IDs with their parents. I over-commented the code, so I won't explain to much.
php Syntax (Toggle Plain Text)
<?php /** * Handles creating and/or printing a Tree-Like HTML output, complete with * all necessary CSS styles. * * Assumes a MySQL database table structure like so: * CREATE TABLE `name` ( * `id` int(11) NOT NULL AUTO_INCREMENT, * `parentID` int(11) DEFAULT NULL, * PRIMARY KEY (`id`) * ); * * Public methods: * createTree - Returns the HTML tree-view. * printTree - Prints the HTML tree-view. * * Private methods * fetchTree - Reads the complete tree structure into an array. * buildHtml - Builds the HTML div hierarchy based. */ class TreeView { private $bgColor = "rgba(0, 100, 0, 0.10)"; private $dbLink; private $tblName; /** * Default constructor * @param mysqli $dbLink A open MySQL (mysqli) connection. * @throws Exception */ public function __construct(mysqli $dbLink) { if($dbLink != null && $dbLink->connect_errno == 0) { $this->dbLink = $dbLink; // This number is added the the container DIV ID, so that we can // tell the DIVs a part if there are more than one view created. if(!isset($GLOBALS['TreeView_DivID'])) { $GLOBALS['TreeView_DivID'] = 0; } } else { throw new Exception("The mysqli object provided is invalid."); } } /** * Creates a descending tree-like view of the tree-structure in the given * database table and returns it as a string. * @param <type> $tblName The name of the database table to use. * @return <string> The string output. * @throws Exception */ public function createTree($tblName) { if(!isset($dbName, $tblName) || (empty($dbName) && empty($tblName))) { throw new Exception("Failed to create the tree. Table or database information is invalid"); } else { // Set up variables $this->tblName = $tblName; $treeData = array(); $output = ""; // Create the output $this->fetchTree($treeData); // 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} div { margin: 0; padding: 0 10px; float: left; background-color: {$this->bgColor}; } div#{$divID} p { margin: 0; padding: 0; } </style> <div id="{$divID}"> HTML; // Add the DIV hierachy. $this->buildHtml($treeData, $output); // Increment the DIV ID number $GLOBALS['TreeView_DivID']++; return $output; } } /** * Prints a descending tree-like view of the tree-structure in the given * database table. * @param <type> $tblName The name of the database table to use. * @throws Exception */ public function printTree($tblName) { echo $this->createTree($tblName); } /** * A recursive function that fetches a tree-structure from a database into an array. * @global <mysqli> $dbLink A open MySQLI connection. * @param <number> $parentID The ID the current recursion uses as a root. */ private function fetchTree(&$parentArray, $parentID=null) { global $dbLink; // Create the query if($parentID == null) { $parentID = -1; } $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()) { // 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); } $result->close(); } else { die("Failed to execute query! ($level / $parentID)"); } } /** * Builds a HTML <div> hierarchy from the tree-view data. * Each parent is encased in a <div> with all their child nodes, and each * of the children are also encased in a <div> with their children. * @param <array> $data The tree-view data from the fetchTree method. * @param <string> $output The <div> hierachy. */ private function buildHtml($data, &$output) { // Add the DIV hierarchy. foreach($data as $_id => $_children) { $output .= "<div><p>{$_id}</p>"; $this->buildHtml($_children, $output); $output .= "</div>"; } } } ?>
Which you could use like so:
php Syntax (Toggle Plain Text)
<!DOCTYPE html> <html> <head> <title>Tree-view Test</title> <meta http-equiv="Content-Type" content="text/html; charset=utf8"> </head> <body> <?php $dbLink = new mysqli("localhost", "usr", "pwd", "dbName"); $treeView = new TreeView($dbLink); $treeView->printTree('tblName'); $dbLink->close(); ?> </body> </html>
P.S.
Don't try this using Internet Explorer. It has a problem rendering CSS rules defined this decade, so the background colors won't show.
Last edited by Atli; 26 Days Ago at 11:30 pm. Reason: Copy/Paste failure xD
Please do not ask for help in a PM. Use the forums.
And use [code] tags!
And use [code] tags!
![]() |
Similar Threads
- PHP & MySQL Error. Please help. (PHP)
- Java recursive binary tree (Java)
- Need Assitance On Php & Mysql test. (PHP)
- Binary Tree store in MYsql? (PHP)
- Banner Free: PHP & MySQL web hosting: 300MB Space & 80 GB Traffic (Web Hosting Deals)
- <script language=\"javascript\"> Display problem with PHP & MYSQL (PHP)
- 250 MB Disk / 40 GB Traffic Free PHP & MySQL Host (Web Hosting Deals)
- php & mysql (MySQL)
- Question about binary tree & heaps (Computer Science)
Other Threads in the PHP Forum
- Previous Thread: Print Multiple Files using PHP
- Next Thread: fetching youtube embed code.......with php
| Thread Tools | Search this Thread |
access ajax ajaxcode ajaxhelp amf api array autoincrement beginner body c# cakephp cheap class cms curl database dehasher delete developer display dropdownlist email files flash form forms gaming glassfish google html ibm image images include innerjoins insert java javascript joomla jquery keywords lamp link linux login mail malfunctioning menu montywidenius msqli_multi_query multiple multipletables mysql mysqlquery oop oracle pdf persist php post programming quality query radio recursiveloop remote root rss script search searchmonkey security select server sms smtp soap source spam sql sqlserver sun support! survey system table traffic trouble tutorial upload video view webdesign website wpf xml ydn youtube zend






