Jump to content

Help with Downline, shows parent but not child


Gotharious

Recommended Posts

Ok, here is the whole code for the downline, but the problem is that it doesn't show members below that one

 

I mean if b follows a, and c follows b and I opened the page of A, it will only show A's info, and not bring B and C in the downline

 

 

<?php

if($_REQUEST["i"]){
GenerateTree($_REQUEST["i"]);
} else{
GenerateTree($_GET['id']);
}

function GenerateTree($memberid){
$l1="<img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' />";$l2="<img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' />";
$query = "SELECT * FROM users where recruiteris='".$memberid."' order by type";
//echo $query;
$result = mysql_query($query);
//var_dump($result);	

while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    	if($row["type"]=="Company"){$l1=getDownline($row["id"]);}
	if($row["type"]=="client"){$l2=getDownline($row["id"]);}
}
mysql_free_result($result);

echo "<table border='0' class='mainTable' cellspacing='0' cellpadding='3' style='width:100%'>\n";
echo "<tr><td colspan='3' style='text-align:center;'>Login ID: ".$memberid.getInfo($memberid)."<br />"."</td></tr>";
echo "<tr><td colspan='3'>".getDownline($memberid)."</td></tr>";
echo "<tr><td style='width:33%;'>".$l1."</td><td style='width:33%;'>".$l2."</td>";
echo "</table>\n";
}

function getDownline($memberid){
$query = "SELECT * FROM users where recruiteris='".$memberid."' order by type";
//echo $query;
$result = mysql_query($query);
//var_dump($result);
$final = "<table border='0' style='width:100%;' class='internalTable' cellspacing='0' cellpadding='2'>\n";
$final .= "<tr>";
$nothing=true; $x=0; $pre;
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
	$x++; $_SESSION['s']=0;
	if($row["type"]=="Company" && $x==1){$final .= "<td style='width:33%; background-color:#FFFFEC;' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";}
	if($row["type"]=="client" && $x==2){$final .= "<td style='width:33%; background-color:#E1F0FF;' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";}
	if($row["type"]=="client" && $x==1){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td><td style='width:33%; background-color:#E1F0FF' title='".getToolTip($row["login_id"])."'><a href='gen.php?i=".$row["login_id"]."'>".$row["login_id"]."</a><br />".$row["m_name"]."<br />Position: ".$row["form_type"]."<br />Downline - ".getCount($row["login_id"]).$_SESSION['s']."</td>";}

	$pre = $row["type"];
	$nothing=false;
}
if($nothing){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td><td style='width:34%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td>"; }
if($x==1 && $pre=="Company"){$final .= "<td style='width:33%'><img src='icon.gif' width='33' height='45' alt='No Record' longdesc='#' /></td>";}
mysql_free_result($result);
$final .= "</tr>";
$final .= "</table>\n";
return $final;
}

function getToolTip($id){
$query = "SELECT * FROM users where id ='".$id."'";
$result = mysql_query($query);
$res;
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    	$res = "fade=[off] cssheader=[toolHeader] cssbody=[toolBody] header=[Detail For ID () - ".$id."] body=[".$row["m_name"]."<br />Address:<br />".$row["address"]."]";
}
mysql_free_result($result);
return $res;
}

function getInfo($id){
$query = "SELECT * FROM users where id='".$id."'";
$result = mysql_query($query);
$res;
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    	$res = "<br />Name: ".$row["fname"]."<br />National ID: ".$row["nid"]."<br />";
}
mysql_free_result($result);
return $res;
}

function getCount($id){
$query = "SELECT * FROM users where recruiteris='".$id."'";
$result = mysql_query($query);
$count = mysql_num_rows($result);

$_SESSION['s'] = $_SESSION['s']+$count;
while ($row = mysql_fetch_array($result, MYSQL_BOTH)) {
    	getCount($row["id"]);
}
mysql_free_result($result);
//echo $count."<br />";
return "";	
}

// Closing connection
mysql_close($link);


?>

Link to comment
Share on other sites

Ok, I've tried a different code, but there is a problem now

it gives me a warning

Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/www/waw-eg.com/admin/tree2.php on line 58

 

the code is

 


<?php
include("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 id,recruiteris,position from `users` where recruiteris="'.$member_id.'" and  position="'.$direction.'"'));
			$getdownline = $getdownlinesql['id'];
			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 id,recruiteris,position from `users` where recruiteris="'.$member_id.'" ORDER BY position');
			while($childdownline = mysql_fetch_array($getchilddownlinesql)){
					$childdownlinecode = $childdownline['id'];
					$direction = $childdownline['position'];
					if($direction=='Left'){
						if($childdownlinecode){
							//this is where you play with your html layout
							echo $childdownlinecode.'<br>';
							GetNextDownlines($childdownlinecode,'Left');
						}
					}

						if($direction=='Right'){
							if($childdownlinecode){
								//this is where you play with your html layout
								echo $childdownlinecode.'<br>';
								GetNextDownlines($childdownlinecode,'Right');
						}
					}
			 }
    }

//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=='Left'){
				$topleft = GetDownline($member_id,'Left');
					if($topleft){
							//this is where you play with your html layout
					echo $topleft.'<br>';
					}
						$getleftdownlinesql = @mysql_query('select id,recruiteris,position from `users` where recruiteris="'.$topleft.'" ORDER BY position');
						while($getleftdownline = mysql_fetch_array($getleftdownlinesql)){
						$leftdownline = $getleftdownline['id'];
						$leftdirection = $getleftdownline['position'];

						if($leftdirection=='Left'){
								if($leftdownline){
							//this is where you play with your html layout
									echo $leftdownline.'<br>';
									GetChildDownline($leftdownline);
								}
						  }

						if($leftdirection=='Right'){
								if($leftdownline){
							//this is where you play with your html layout
								echo $leftdownline.'<br>';
								 GetChildDownline($leftdownline);
								 }
						   }
						 }
		}


		if($direction=='Right'){
					$topright = GetDownline($member_id,'Right');
					if($topright){
					echo $topright.'<br>';
					}
					$getrightdownlinesql = @mysql_query('select id,recruiteris,position from `users` where recruiteris="'.$topright.'" ORDER BY position');
					while($getrightdownline = @mysql_fetch_array($getrightdownlinesql)){
								$rightdownline = $getrightdownline['id'];
								$rightdirection = $getrightdownline['position'];

								if($rightdirection=='Left'){
										if($rightdownline){
							//this is where you play with your html layout
										echo $rightdownline.'<br>';
										GetChildDownline($rightdownline);
										}
								}

								if($rightdirection=='Right'){
										if($rightdownline){
							//this is where you play with your html layout
										echo $rightdownline.'<br>';
										GetChildDownline($rightdownline);
										}
								}

						}
			}
}

?>
<html>
<head>
<title>Winner And Winner</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,'Left');
GetNextDownlines($topmcode,'Right');
?>

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

Link to comment
Share on other sites

Get rid of the @error suppression operator in your code, and forget it even exists. If there's an error you need to know about it.

 

Don't nest a bunch of mysql_* functions together. It makes debugging next to impossible.

 

Form your query string in a variable and use the variable in the query execution. Then you can echo the query string to debug it.

 

Make use of mysql_error, by echoing it with the query string when a query fails.

Link to comment
Share on other sites

I don't think I get what you mean by "form a query string......."

 

would you kindly give an example?

 

about nesting, it was suggested by thrope that I use nested sets and that's all the info I found about it online that suits what I'm trying to do tho

Link to comment
Share on other sites

Ok, I've tried another thing now, a code posted by someone on the internet, everyone says it's working and seen screenshots of people who used it and it's great.

 

the problem now, is that when I try to view the page, it only gives me "40" as a result, no trees, nothing

 

I'm posting the code below for the php

 

tree2.php


<!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">
            // Have the TreeView.drawAll method executed as soon as the DOM is ready.
            $(document).ready(function(){ 
                TreeView.drawAll();
            });
        </script>
    </head>
    <body>
        <?php
        // 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", "user", "password", "database");

        // Create an instance of the TreeView class.
        $treeView = new TreeView($dbLink);

        // Print the tree view
        // TODO: Insert your real table name here.
        $treeView->printTree('users');

        $dbLink->close();
        ?>
    </body>
</html>

 

class.TreeView.php

 

 


<?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 = ""; //"background-color: 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($tblName) || 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; {$this->bgColor}}
    div#{$divID} p   { margin: 0; padding: 0; margin-bottom: 10px; }
</style>
<div id="{$divID}">
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

<script type="text/javascript">
TreeView.addTree('Tree{$GLOBALS['TreeView_DivID']}_{$rootID}');
</script>
HTML;

            // 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 = 0;
        }
        $sql = "SELECT `id` FROM `{$this->tblName}` WHERE `recruiteris`= ". 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 id=\"Tree{$GLOBALS['TreeView_DivID']}_{$_id}\"><p>{$_id}</p>";
            $this->buildHtml($_children, $output);
            $output .= "</div>";
        }
    }
}
?>

 

TreeView.js

 


/**
* Handles drawing lines between the tree structures generated by PHP.
*/
var TreeView =
{
    /** Constants (sort of) **/
    LINE_MARGIN : 10, // px
    BORDER_STYLE : "solid 1px #555555",

    /** 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));
    }
}

 

 

Now my recruiter ID in the database is recruiteris and the user ID is id

Link to comment
Share on other sites

Forming query strings in a variable:

$query = "SELECT field1, field2 FROM table WHERE some_field = 'some_value'";
$result = mysql_query($query);

 

I don't believe thorpe would have suggested nesting all the functions together like that. With the errors suppressed, and all of the functions nested together, you have no easy way to debug it. For your first function, I'd do something more like this:

// bad way
$getdownlinesql = @mysql_fetch_assoc(@mysql_query('select id,recruiteris,position from `users` where recruiteris="'.$member_id.'" and  position="'.$direction.'"'));

// good way
$query = "SELECT id, recruiteris, position FROM `users` WHERE recruiteris = '$member_id' AND position = '$direction'";
if( !$result = mysql_query($query) ) {
     echo "<br>Query: $query<br>Failed with error: " . mysql_error();
     return FALSE;
} else {
     $array = mysql_fetch_assoc($result);
     return $array['id']
}

Link to comment
Share on other sites

I'm not sure if this is right, but I get no results from this

 

<?php
    function GetDownline($member_id,$direction) 
    { 
    	    $query = ("SELECT id, recruiteris, position FROM `users` WHERE recruiteris = '$member_id' AND position = '$direction'");
if( !$result = mysql_query($query) ) {
     echo "<br>Query: $query<br>Failed with error: " . mysql_error();
     return FALSE;
} else {
     $array = mysql_fetch_assoc($result);
     $getdownline =  $array['id'];
     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;

$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;
?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.