-1

How to output the red color level on each member's name like the following screenshot : enter image description here

Here is the demo webpage URL : http://client.bfm.expert/test_UnilevelBonus.php

Here is the code :

<?php
ini_set('display_errors', 1); 
ini_set('display_startup_errors', 1); 
error_reporting(E_ALL);

//Use the following function to get the data of downlines
function getChildren($parent) {
    $servername = "11";
    $username = "11";
    $password = "11";
    $dbname = "11";

    $conn = new mysqli($servername, $username, $password, $dbname);
    if ($conn->connect_error) {
        die("Connection failed: " . $conn->connect_error);
    }

    $query = "SELECT user_id, first_name, sponsor_id FROM tbl_user_master WHERE sponsor_id = $parent";
    $result = $conn->query($query);
    $children = array();
    $i = 0;
     $result = $conn->query($query) or die($conn->error);
    while($row = $result->fetch_assoc()) {

        $children[$i] = array();
        $children[$i]['name'] = $row['first_name'];
        $children[$i]['children'] = getChildren($row['user_id']);

    $i++;
    }
return $children;

$conn->close();
}



//enter sponsor_id here, change 151 to 145 has a lot of downlines to test
$finalResult = getChildren(145);




//display all downlines of the sponsor
function printList($array = null) {
    if (count($array)) {
        echo "<ul>";

        foreach ($array as $item) {
            echo "<li>";
            echo $item['name'];
            echo " - level : ";
            if (count($item['children'])) {
                printList($item['children']);
            }
            echo "</li>";
        }

        echo "</ul>";
    }
}

printList($finalResult);

?>
zac1987
  • 2,721
  • 9
  • 45
  • 61
  • 5
    Your code is vulnerable to [**SQL injection**](https://en.wikipedia.org/wiki/SQL_injection) attacks. Instead of building queries with string concatenation, always use [**prepared statements**](https://secure.php.net/manual/en/pdo.prepare.php) with [**bound parameters**](https://secure.php.net/manual/en/pdostatement.bindparam.php). See [**this page**](https://phptherightway.com/#databases) and [**this post**](https://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php) for some good examples. – Alex Howansky Jan 05 '20 at 19:41

1 Answers1

1

You need to pass level into 'printList' function and increment it after.

function printList($array = null, $level = 1) {
    if (count($array)) {
        echo "<ul>";

        foreach ($array as $item) {
            echo "<li>";
            echo $item['name'];
            echo " - level : " . $level;
            if (count($item['children'])) {
                printList($item['children'], $level+1);
            }
            echo "</li>";
        }

        echo "</ul>";
    }
}

printList($finalResult, 1);
vonschlager
  • 324
  • 1
  • 6