-1

This is my table datas and rows

users     under_userid 
-------   ------------
demo        NULL  
user1       demo 
user2       user1 
user3       user1 
user4       user2

I have tried a query as below

$query = mysqli_query($con,"select under_userid from user where  users='user4'");    
$result = mysqli_fetch_array($query);
foreach ($result as $x => $x_value)
{            
  echo 'Value = ' . $x_value;      
}

I got a output for above statement

Value = user2

But I need to all under_userid from Output Value

Expected Output
 Value = user2
 Value = user1
 Value = demo

How to get all under_userid from Output Value?
Then I need a Correct MySQL query and Loop Statement using Php?

Pierre François
  • 5,850
  • 1
  • 17
  • 38
Vicky
  • 25
  • 7
  • http://mikehillyer.com/articles/managing-hierarchical-data-in-mysql/ – Barmar Feb 13 '18 at 10:08
  • You need to repeat the query recursively, using the result from the previous query as the `WHERE` clause in the next one. – Barmar Feb 13 '18 at 10:09
  • Mr.Barmar ,I have tried above query but i am getting only one under_userid but i need to get all under_userid so can you give me a query, loop statement and how to fetch all rows from query – Vicky Feb 13 '18 at 10:13
  • @Barmar you can see my above output and Expected output – Vicky Feb 13 '18 at 10:14
  • You need to explain more clearly what you're trying to do, people don't understand your example. They think you want to print all the `under_userid` except `NULL`. You should include rows that aren't part of the chain. – Barmar Feb 13 '18 at 10:25
  • Possible duplicate of [Finding all parents in mysql table with single query (Recursive Query)](https://stackoverflow.com/questions/12948009/finding-all-parents-in-mysql-table-with-single-query-recursive-query) – USER249 Feb 13 '18 at 10:36

2 Answers2

0

You need a recursive function:

function get_all_under($con, $userid) {
    $stmt = mysqli_prepare($con, "SELECT under_userid FROM user where user = ? AND under_userid IS NOT NULL");
    mysqli_stmt_bind_param($stmt, "s", $userid);
    mysqli_stmt_execute($stmt);
    mysqli_stmt_bind_result($stmt, $under_userid);
    $results = array();
    while (mysqli_stmt_fetch($stmt)) {
        echo "Value = $under_userid<br>";
        $results[] = $under_userid;
    }
    // Now get the next level
    foreach ($results as $under_userid) {
        get_all_under($con, $user_userid);
    }
}

get_all_under("user4");
Barmar
  • 741,623
  • 53
  • 500
  • 612
-1

Replace your query with:

SELECT under_userid FROM user WHERE under_userid !=  'NULL'