| | |
Binary Tree Using PHP & MySQL
Please support our PHP advertiser: PostgreSQL or MySQL? Compare and contrast the two most popular open source databases
![]() |
0
#11 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 rightPHP 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
Thank You For Your Help..
Your Code is Work Fine and Very Helpful for Me.
but I Have Some Trouble in The Above Code. I Have Created a Page Called http://www.liferider.info/mlm/tree.php This Page Create Tree View from Your Above Given Code.
This Code Have a Bug That This Print all Node in Every Section of Binary Tree.
Please Check the above Page for Illustration.
Please Tell me How I Can Print only Child Node in Binary Tree. my Database Schema is Given Below:
PHP Syntax (Toggle Plain Text)
| memid | | placementid | | position | | 1 | | 0 | | 0 | | 2 | | 1 | | L | | 3 | | 1 | | R | | 4 | | 2 | | L | | 5 | | 2 | | R | | 6 | | 3 | | L | | 7 | | 3 | | R | | 8 | | 4 | | L | | 9 | | 4 | | R | | 10 | | 5 | | L | | 11 | | 5 | | R | | 12 | | 6 | | L | | 13 | | 6 | | R | | 14 | | 7 | | L | | 15 | | 7 | | R |
Last edited by hemgoyal_1990; 27 Days Ago at 5:29 am.
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
#12 25 Days Ago
Please Help..
I am Very Much Need Help...
I am Very Much Need Help...
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
#13 23 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.
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:
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 xDphp 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.
Friedn Could You Tell me That Where I Put Table name in The Above Code.
I am Created a Table Called mlm_data with Below Field:
PHP Syntax (Toggle Plain Text)
ID parentID 1 0 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 4 10 5 11 5 12 6 13 6 14 7 15 7
Please Help me It's Very Urgent.
Last edited by hemgoyal_1990; 23 Days Ago at 5:01 am.
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
#15 23 Days Ago
I Put the Table name where u specified and run my code but there nothing print..
in below url format:
http://yourdomain.com/mlm/tree.php
is there the above url is right or may change the url.
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
#16 23 Days Ago
Did you include the class or just put it at the top of the page?
Ideally, you would put the class (the first code I posted in post #10) into a file, lets call it "class.TreeView.php".
Then you create your tree file, "tree.php", and you put this into it:
In that code, you need to fill out both the MySQL database info and replace the 'tblName' with the name of your table.
Ideally, you would put the class (the first code I posted in post #10) into a file, lets call it "class.TreeView.php".
Then you create your tree file, "tree.php", and you put this into it:
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 // Turn on error reporting, just in case. ini_set('display_errors', true); error_reporting(E_ALL); // Fetch the TreeView class from the other file. include("class.TreeView.php"); // Open a database connection // TODO: Replace the info here with your real info. $dbLink = new mysqli("localhost", "usr", "pwd", "dbName"); // Create an instance of the TreeView class. $treeView = new TreeView($dbLink); // Print the tree view // TODO: Insert your real table name here. $treeView->printTree('tblName'); $dbLink->close(); ?> </body> </html>
Please do not ask for help in a PM. Use the forums.
And use [code] tags!
And use [code] tags!
0
#17 23 Days Ago
Ohh, I just realized, there is a bug in my class.
Line #60. Replace it with:
Minor oversight. Sorry ;-)
Line #60. Replace it with:
php Syntax (Toggle Plain Text)
if(!isset($tblName) || empty($tblName))
Minor oversight. Sorry ;-)
Last edited by Atli; 23 Days Ago at 1:44 pm.
Please do not ask for help in a PM. Use the forums.
And use [code] tags!
And use [code] tags!
0
#18 22 Days Ago
i am compile my code with your guideline and follow that there are nothing print. i think there are some mistake in my database structure.
i am using the below table structure:
i am using the below table structure:
PHP Syntax (Toggle Plain Text)
id parentID 1 0 2 1 3 1 4 2 5 2 6 3 7 3 8 4 9 4 10 5 11 5 12 6 13 6 14 7 15 7
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
#20 21 Days Ago
Thanx Atil for Helping me Out.
I am Very Thankful for You. You Solve my Very big Problem.
I am Very Thankful for You. You Solve my Very big Problem.
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.
![]() |
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 |
ajax api array aws beginner broken c# calendar class cms code codes curl database display downloader dropdown email error errorlog execution explodefunction files flash flex folder form forms gentoo google head hosting html ibm image include insert java javascript jquery js keywords kickfire link links linux login mail mariadb matching memmory menu migrate mimic multiple mysql mysql.data.client mysqlquery nodes object oop open oracle parsing php post programming query radio recourse script search security select seo server simple simpledb sms spam speed sql subscription sun syntax table tag tutorial up-to-date upload user variable vbulletin video virus webbrowser window yahoo youtube zend






