Question

I'm having a problem to show users in my referral system.

If you look at table you'll notice userid '29' was refered by '28'; and '28' by '26'; also '26' by '10'

When user session '29' is active the page should display above users. Hope you got the idea.

Referal table:

enter image description here

Code:

<?php
$rs=mysql_query("select userid from referal where refereduserid='29'") or  die(mysql_error());
$exitloopcount=mysql_num_rows($rs);
$last=mysql_fetch_array($rs);
if ($exitloopcount>0) 
{
  for($i=0;$i<$exitloopcount;$i++)
  {
    $rs=mysql_query("select userid from referal where refereduserid='".$last[$i]."'");
    while($data=mysql_fetch_array($rs))
    {
      echo $data[$i];
    } 
  }
}
?>
Was it helpful?

Solution

This should be able to done by one single query (like Oracle's CONNECT BY clause), but I'm not familiar with MySQL, so I'm offering you the alternative solution, as you will be told "don't use mysql_* functions anymore" by someone here.

This solution uses MySQLi instead of the deprecated mysql_* function collection.

$stmt=$mysqli->prepare("SELECT `userid` FROM `referal` WHERE `refereduserid`=?");
$stmt->bind_param("i",$id); //here $id=29
$stmt->execute();
$result=$stmt->get_result();
while($row=$result->fetch_assoc())
{
    echo $row["userid"];
    $id=intval($row["userid"]);
    $stmt->bind_param("i",$id);
    $stmt->execute();
    $result=$stmt->get_result();
}

Edit:

Explanation:

One thing about MySQLi and PDO is that they supports prepared statement.

As this is a chained relationship (and thankfully a one-to-one one), I can simply prepare one query:

SELECT `userid` FROM `referal` WHERE `refereduserid`=?

this query will be used to continuously fetched the "referrer".

Then we bind the "initiate" id, 29, and executes the query.

While a "referrer" is found, echo it out (as demonstrated in your code), and then re-bind it to the prepared query, and executes it to find its "referrer". Continue this step.

Using the sample date in your question:

  1. bind: 29 -> executes -> get: 28
  2. bind: 28 -> executes -> get: 26
  3. bind: 26 -> executes -> get: 10
  4. bind: 10 -> executes -> no result
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top