在PHP和MySQL的mlm模块中获取我下面的所有成员

e0bqpujr  于 2023-01-08  发布在  PHP
关注(0)|答案(1)|浏览(104)

我有一个数据库,如下所示,任何用户都可以使用任何赞助商ID加入,他们将获得自己的用户ID,这可以进一步引导树。我想获得特定user_id的详细信息,比如说,“2”。我需要user_id将在其中的输出(3,4,因为3直接与2链接,并且4直接与3链接,32链接)。类似地,如果我选择user_id1,然后得到结果user_id2,3,4,5,其中25直接链接到user_id13,4间接链接到1)。
我尝试了几乎所有可能的while循环格式,但就是不能得到输出。下面是我代码的最后一部分,因为我删除了大部分:

<?php
include 'config.php';
$current_user='1';

$all = mysqli_query($con,"SELECT * FROM users");
while($all_array = mysqli_fetch_array($all)){
    $all_sponsors = $all_array['sponsor_id'];
}

$below_details = mysqli_query($con,"SELECT * FROM users WHERE sponsor_id ='$current_user'");
while ($below_array = mysqli_fetch_array($below_details)){
    $below_users = $below_array['user_id']; 
    }
?>

任何形式的帮助都是感激的。如果问题中有任何困惑,请随时向我询问细节。

fdx2calv

fdx2calv1#

您可以使用递归CTE来检索给定ID下的所有成员-

WITH RECURSIVE pyramid AS (
    SELECT u.* FROM users u WHERE sponsor_id = 1 /* starting sponsor_id */
    UNION ALL
    SELECT u.* FROM pyramid p JOIN users u ON p.id = u.sponsor_id
)
SELECT * FROM pyramid;

相关问题