MLM Software

How to create an MLM genealogy tree?

A Complete Guide to Building Binary, Unilevel, Matrix, and Multi-Level Genealogy Trees Using PHP and MySQL

25 November 2026 46 Views 0 Likes 0 Comments
How to Create an MLM Genealogy Tree Using PHP and MySQL

How to Create an MLM Genealogy Tree Using PHP and MySQL?

Introduction

An MLM genealogy tree is one of the most important components of Multi-Level Marketing (MLM) software. It displays the hierarchical relationship between members and helps administrators and distributors track their network structure, referrals, placements, and downline members.

Whether you are developing Binary MLM, Unilevel MLM, Matrix MLM, or Forced Matrix MLM software, a properly designed genealogy system is essential for managing the entire network.

PHP and MySQL provide a flexible technology stack for developing dynamic MLM genealogy trees. PHP handles member registration, placement logic, and database operations, while MySQL stores sponsor relationships, parent-child connections, and genealogy records.

In this guide, we will explain how to create an MLM genealogy tree using PHP and MySQL, with practical database structures, SQL queries, PHP examples, and frontend visualization techniques.

1. Understand the MLM Genealogy Structure

Before developing an MLM genealogy tree, you must understand how different MLM plans organize their members.

There are several popular genealogy structures.

Binary MLM Tree

In a Binary MLM plan, each member can have a maximum of two downline positions:

  • Left Position

  • Right Position

Example:

                    ADMIN
                   /     \
                USER A   USER B
                /   \     /   \
             USER C USER D USER E USER F

Each member can have two children, and the network can continue across multiple levels.

Unilevel MLM Tree

In a Unilevel MLM plan, one sponsor can directly refer unlimited members.

                   ADMIN
              /     |     \
          USER A  USER B  USER C
          /  \       |       \
       USER D USER E USER F   USER G

Matrix MLM Tree

In a Matrix MLM plan, each member has a fixed number of positions at every level.

For example, a 3×3 matrix allows:

  • 3 positions at Level 1.

  • 9 positions at Level 2.

  • 27 positions at Level 3.

Forced Matrix MLM Tree

In a Forced Matrix plan, members are automatically placed into available positions according to predefined placement rules, even when they were sponsored by another member.

The placement structure and sponsorship structure may therefore be different.

2. Design the MySQL Database Structure

Database architecture is the foundation of an MLM genealogy system.

One important rule is that you should maintain sponsor relationships separately from genealogy placement relationships.

For example:

  • Sponsor ID identifies who referred the member.

  • Parent ID identifies where the member is placed in the genealogy tree.

  • Position identifies whether the member occupies the Left or Right position.

This separation is especially important for Binary and Forced Matrix MLM software.

Create the Users Table

This table stores member registration information.

CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id VARCHAR(50) NOT NULL UNIQUE,
    sponsor_id VARCHAR(50) DEFAULT NULL,
    name VARCHAR(150) NOT NULL,
    email VARCHAR(150) DEFAULT NULL,
    mobile VARCHAR(20) DEFAULT NULL,
    password VARCHAR(255) NOT NULL,
    status TINYINT DEFAULT 1,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    INDEX idx_sponsor (sponsor_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Create the Binary Tree Table

This table stores the actual genealogy placement structure.

CREATE TABLE binary_tree (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_id VARCHAR(50) NOT NULL,
    parent_id VARCHAR(50) DEFAULT NULL,
    position ENUM('L','R') DEFAULT NULL,
    created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,

    UNIQUE KEY unique_user (user_id),
    UNIQUE KEY unique_position (parent_id, position),
    INDEX idx_parent (parent_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

Column explanations:

Column Purpose
id Unique record ID
user_id Member's unique ID
parent_id Parent member ID
position Left or Right
created_at Placement date

The unique position constraint prevents two members from occupying the same non-NULL parent position.

The root member should have a NULL parent and NULL position. Your application should enforce a single root.

3. Insert the Root Member into the Genealogy Tree

The root member is the starting point of the genealogy network.

For example, suppose your administrator's member ID is ADMIN001.

INSERT INTO binary_tree
(user_id, parent_id, position)
VALUES
('ADMIN001', NULL, NULL);

Now ADMIN001 becomes the root of the Binary MLM genealogy tree.

All other members will be placed below this root member.

4. Develop the Binary MLM Placement System Using PHP

After creating the database tables, the next step is developing the member placement system.

When a new member registers, the software should:

  1. Validate the sponsor ID.

  2. Generate a unique member ID.

  3. Identify the placement parent.

  4. Check Left and Right availability.

  5. Insert the member into the genealogy tree.

  6. Save the sponsor relationship.

  7. Commit the database transaction.

Database Connection

Create a file named db.php.

<?php

$host = "localhost";
$dbname = "mlm_database";
$username = "root";
$password = "";

try {

    $pdo = new PDO(
        "mysql:host=$host;dbname=$dbname;charset=utf8mb4",
        $username,
        $password
    );

    $pdo->setAttribute(
        PDO::ATTR_ERRMODE,
        PDO::ERRMODE_EXCEPTION
    );

    $pdo->setAttribute(
        PDO::ATTR_EMULATE_PREPARES,
        false
    );

} catch (PDOException $e) {

    die("Database connection failed.");

}
?>

Binary Placement PHP Function

Create a function to place a new member under an available parent.

<?php

function placeBinaryMember(
    PDO $pdo,
    string $newUserId,
    string $parentId
) {

    try {

        $pdo->beginTransaction();

        // Lock parent record to prevent concurrent placement.
        $stmt = $pdo->prepare("
            SELECT user_id
            FROM binary_tree
            WHERE user_id = ?
            FOR UPDATE
        ");

        $stmt->execute([$parentId]);

        if (!$stmt->fetch()) {
            throw new Exception("Invalid parent member.");
        }

        // Check available positions.
        $stmt = $pdo->prepare("
            SELECT position
            FROM binary_tree
            WHERE parent_id = ?
        ");

        $stmt->execute([$parentId]);

        $positions = $stmt->fetchAll(
            PDO::FETCH_COLUMN
        );

        $position = null;

        if (!in_array('L', $positions, true)) {

            $position = 'L';

        } elseif (!in_array('R', $positions, true)) {

            $position = 'R';

        } else {

            throw new Exception(
                "Both positions are already occupied."
            );

        }

        // Insert genealogy placement.
        $stmt = $pdo->prepare("
            INSERT INTO binary_tree
            (user_id, parent_id, position)
            VALUES (?, ?, ?)
        ");

        $stmt->execute([
            $newUserId,
            $parentId,
            $position
        ]);

        $pdo->commit();

        return [
            'status' => true,
            'position' => $position
        ];

    } catch (Throwable $e) {

        if ($pdo->inTransaction()) {
            $pdo->rollBack();
        }

        return [
            'status' => false,
            'message' => $e->getMessage()
        ];

    }

}
?>

This example uses direct placement under the selected parent. A production application should also implement eligibility checks, sponsor validation, retry handling, and a defined placement policy.

For automatic spillover, the application must search for the next available eligible position instead of stopping when both positions are occupied.

5. Implement the Binary MLM Spillover System

Spillover is an important feature in many Binary MLM plans.

When a selected placement parent already has two members, the system searches for an available position further down the genealogy.

Example:

                     ADMIN
                    /     \
                 USER A   USER B
                 /   \
              USER C USER D
              /
           USER E

Suppose ADMIN has both positions occupied.

The software may automatically place a new member under USER A or another eligible member according to the configured placement policy.

Spillover Placement Logic

A basic breadth-first search can be implemented using PHP.

<?php

function findAvailablePosition(
    PDO $pdo,
    string $startParent
) {

    $queue = [$startParent];

    while (!empty($queue)) {

        $current = array_shift($queue);

        $stmt = $pdo->prepare("
            SELECT position, user_id
            FROM binary_tree
            WHERE parent_id = ?
        ");

        $stmt->execute([$current]);

        $children = $stmt->fetchAll(
            PDO::FETCH_ASSOC
        );

        $occupied = [];

        foreach ($children as $child) {

            $occupied[$child['position']] =
                $child['user_id'];

        }

        // Check left position first.
        if (!isset($occupied['L'])) {

            return [
                'parent_id' => $current,
                'position' => 'L'
            ];

        }

        // Check right position.
        if (!isset($occupied['R'])) {

            return [
                'parent_id' => $current,
                'position' => 'R'
            ];

        }

        // Add children to queue.
        $queue[] = $occupied['L'];
        $queue[] = $occupied['R'];

    }

    return false;

}
?>

This function searches level by level and returns the first available position, checking Left before Right.

For production use, the search and insertion must happen within a transaction with suitable locking and retry handling. Otherwise, concurrent registrations may select the same available position.

6. Calculate Total Downline Members

The genealogy system should provide accurate downline information for every member.

For example, if ADMIN001 has 50 members below the account, the dashboard should display:

Total Downline: 50

For MySQL 5.7 and older versions that do not support recursive CTEs, you can use PHP to traverse the tree.

PHP Downline Counting Function

<?php

function countDownline(
    PDO $pdo,
    string $userId
) {

    $total = 0;
    $queue = [$userId];

    while (!empty($queue)) {

        $current = array_shift($queue);

        $stmt = $pdo->prepare("
            SELECT user_id
            FROM binary_tree
            WHERE parent_id = ?
        ");

        $stmt->execute([$current]);

        $children = $stmt->fetchAll(
            PDO::FETCH_COLUMN
        );

        foreach ($children as $child) {

            $total++;

            $queue[] = $child;

        }

    }

    return $total;

}
?>

Usage:

$totalMembers = countDownline(
    $pdo,
    'ADMIN001'
);

echo "Total Downline: " . $totalMembers;

For large networks, use indexed queries, batch loading, pagination, and cached counts to improve performance.

7. Calculate Left and Right Team Members

Binary MLM software generally displays separate Left and Right team counts.

Example:

                  ADMIN
                 /     \
              LEFT     RIGHT
               25        20

You can calculate the immediate team sizes by traversing each branch.

<?php

$leftCount = countDownline($pdo, 'LEFT001');
$rightCount = countDownline($pdo, 'RIGHT001');

echo "Left Team: " . $leftCount;
echo "Right Team: " . $rightCount;

?>

Here, LEFT001 and RIGHT001 represent the actual member IDs occupying the root's left and right positions.

In a production system, retrieve these IDs from the binary_tree table rather than hardcoding them.

8. Develop the Dynamic MLM Genealogy Tree Visualization

After completing the database and placement logic, you need to display the genealogy tree on the member dashboard.

A good genealogy interface should include:

  • Member ID.

  • Member name.

  • Profile picture.

  • Left and Right positions.

  • Active and inactive status.

  • Total downline.

  • Direct sponsor information.

  • Expand and collapse functionality.

You can use HTML, CSS, JavaScript, Bootstrap 5, and AJAX to create a dynamic genealogy interface.

Example HTML Structure

<div class="genealogy-tree">

    <ul>
        <li>

            <div class="member-box">
                <strong>ADMIN001</strong>
                <span>Administrator</span>
            </div>

            <ul>

                <li>
                    <div class="member-box">
                        <strong>USER001</strong>
                        <span>Left Member</span>
                    </div>
                </li>

                <li>
                    <div class="member-box">
                        <strong>USER002</strong>
                        <span>Right Member</span>
                    </div>
                </li>

            </ul>

        </li>
    </ul>

</div>

CSS for Genealogy Tree

.genealogy-tree ul {
    padding-top: 25px;
    position: relative;
    display: flex;
    justify-content: center;
}

.genealogy-tree li {
    list-style: none;
    text-align: center;
    position: relative;
    padding: 25px 10px 0;
}

.member-box {
    display: inline-block;
    min-width: 120px;
    padding: 15px;
    background: #ffffff;
    border: 2px solid #2563eb;
    border-radius: 12px;
    box-shadow: 0 4px 12px rgba(0,0,0,.08);
}

.member-box strong {
    display: block;
    color: #1d4ed8;
}

.member-box span {
    display: block;
    font-size: 12px;
    margin-top: 5px;
    color: #64748b;
}

For a real application, generate the tree nodes dynamically from database records instead of hardcoding member IDs.

9. Develop AJAX-Based Genealogy Expansion

Displaying thousands of members simultaneously can create performance problems.

A better approach is to load only the first few levels and fetch additional members when a user clicks an expand button.

Example JavaScript:

function loadChildren(userId) {

    $.ajax({

        url: "get_genealogy.php",

        type: "POST",

        data: {
            user_id: userId
        },

        dataType: "json",

        success: function(response) {

            if (response.status) {

                console.log(response.members);

                // Render child members here.

            }

        }

    });

}

The PHP endpoint should:

  1. Verify the logged-in member.

  2. Check whether the requested member belongs to an accessible genealogy.

  3. Fetch the immediate children.

  4. Return JSON data.

  5. Allow the frontend to render the new nodes.

Use authentication, authorization, CSRF protection, and server-side access checks. Never trust a member ID submitted by the browser.

10. Develop the Unilevel Genealogy Tree

A Unilevel MLM structure is different from Binary MLM because members can have unlimited direct referrals.

Example:

                    ADMIN
          ___________|____________
         /           |            \
      USER A       USER B        USER C
      /   \          |             \
   USER D USER E   USER F         USER G

For Unilevel MLM, you can store the sponsor relationship directly in the users table.

Example SQL:

SELECT
    user_id,
    name,
    sponsor_id
FROM users
WHERE sponsor_id = 'ADMIN001';

This query retrieves the direct referrals of ADMIN001.

For deeper downline calculations, traverse sponsor relationships level by level using PHP or maintain a dedicated closure table.

11. Develop the Matrix MLM Genealogy Tree

Matrix MLM uses a predefined width and depth.

For example, a 3×3 matrix allows:

Level Maximum Members
Level 1 3
Level 2 9
Level 3 27
Total 39

The maximum number of positions can be calculated using:

Total Positions = Width + Width² + ... + Width^Depth

For a 3×3 matrix:

3 + 9 + 27 = 39 positions.

Your placement engine must check the matrix capacity and assign members according to the defined placement rules.

12. Optimize the Genealogy Database for Large Networks

A successful MLM system may contain thousands or millions of members.

Database performance becomes increasingly important as the genealogy grows.

Follow these optimization practices:

  1. Add indexes to user_id and parent_id.

  2. Use InnoDB for transactional integrity.

  3. Avoid loading the entire genealogy at once.

  4. Use AJAX for additional levels.

  5. Cache frequently requested downline counts.

  6. Use batch queries instead of querying each member individually.

  7. Maintain separate sponsor and placement relationships.

  8. Use background jobs for large reports.

  9. Avoid unnecessary database updates.

  10. Monitor query execution time.

For very large networks, a closure table or materialized path approach can make ancestor and descendant queries more efficient.

13. Implement Security in the MLM Genealogy System

Security is important because genealogy information is part of the business's sensitive member data.

Important security measures include:

  • Use PDO prepared statements.

  • Validate member IDs.

  • Implement role-based permissions.

  • Prevent unauthorized genealogy access.

  • Protect AJAX endpoints.

  • Use CSRF tokens.

  • Validate all database operations.

  • Maintain audit logs for placement changes.

  • Prevent duplicate member placement.

  • Use transactions for registration and placement.

Never allow ordinary members to modify their own parent ID or genealogy position directly.

14. Test the Complete MLM Genealogy System

Before deploying your MLM software, test the following scenarios:

  • Root member creation.

  • Left and Right placement.

  • Duplicate position prevention.

  • Sponsor ID validation.

  • Automatic spillover.

  • Direct referral counting.

  • Total downline counting.

  • Left and Right team counting.

  • Matrix placement restrictions.

  • Genealogy expansion using AJAX.

  • Large network performance.

  • Member access permissions.

  • Concurrent member registration.

Testing concurrent registrations is especially important because multiple users may attempt to occupy the same position simultaneously.

Conclusion

Creating an MLM genealogy tree using PHP and MySQL requires proper database architecture, member relationship management, placement algorithms, spillover logic, and dynamic frontend visualization.

Whether you are developing Binary MLM, Unilevel MLM, Matrix MLM, or Forced Matrix MLM software, the genealogy structure must accurately represent member relationships and follow the business's predefined placement rules.

A well-designed genealogy system helps administrators monitor network growth, enables members to understand their downline, and provides a strong foundation for commission calculations and business reporting.

Looking for Professional MLM Software Development?

Togle.in provides custom MLM software development solutions for different network marketing business models.

Our development solutions include:

  • Binary MLM Software

  • Unilevel MLM Software

  • Matrix MLM Software

  • Forced Matrix MLM Software

  • Generation MLM Software

  • Hybrid MLM Software

  • Custom MLM Genealogy Tree Development

Whether you need a new MLM platform or want to customize an existing system, Togle.in can help you build a flexible PHP and MySQL-based MLM solution.

???? Website: https://togle.in/

Contact Togle.in for Custom MLM Software Development.

Share this article
JOIN THE DISCUSSION

Like & Comments

Found this article helpful? Share your thoughts with us.

Leave a comment

Comments are reviewed before publishing.

Comments 0

No comments yet. Be the first to comment!