title: how to count members in 15 level deep for each level in php
body: <p>I am badly in need of counting every member on each level I have 15 level deep Commission model so I am able to count the first level but not able to count the whole team a person have in his / her down line. I want to count how many members on each level.
  like on 1st level 10 members, second level 55 members, third level 35 members etc. 
  I need to count the whole number of members for Parent id on 1st level, 2nd level ... up to 15th level.
  I am able to count on the first level like</p>
  
  <pre><code>$result = mysqli_query($con, "SELECT count(*) FROM affiliateuser where referedby = '" . $_SESSION['username'] . "' AND active = 1");
  </code></pre>
  
  <p>if you need any clarification please comment I will explain.
  I am sharing my first 2 Level code here. Please check the code below.</p>
  
  <blockquote>
    <p>started Fetching 1st level of downline users </p>
  </blockquote>
  
  <pre><code>$totalref = 0;
  $totalrefear = 0;
  $query = "SELECT fname,email,doj,active,username,level,pcktaken FROM affiliateuser where referedby = '" . $_SESSION['username'] . "'";
  $result = mysqli_query($con, $query);
  while($row = mysqli_fetch_array($result)) {
      $ac = "$row[active]";
      $countusername = "$row[username]";
      $countuserlevel = "$row[level]";
      $pcktook = "$row[pcktaken]";
  }
  </code></pre>
  
  <blockquote>
    <p>started Fetching 2nd level of downline users</p>
  </blockquote>
  
  <pre><code>$totalrefear = 0;
  $query = "SELECT fname,email,doj,active,level,username FROM affiliateuser where referedby = '" . $_SESSION['username'] . "'";
  $result = mysqli_query($con, $query);
  while($row = mysqli_fetch_array($result)) {
      $ac = "$row[active]";
      $countusername = "$row[username]";
      $countuserlevel = "$row[level]";
      $query2level = "SELECT fname,email,doj,active,level,username,pcktaken FROM affiliateuser where referedby = '$countusername'";
      $result2level = mysqli_query($con, $query2level);
      while($row2 = mysqli_fetch_array($result2level)) {
          $ac2 = "$row2[active]";
          $countusername2 = "$row2[username]";
          $countuserlevel2 = "$row2[level]";
          $pcktook = "$row2[pcktaken]";
      }
  }
  </code></pre>
  
  <p>I am trying with this query for counting users in the 2nd level of the parent. But it's counting me whole database users. I just want to count 2nd level users.any body help me solve it, please?</p>
  
  <pre><code>$queryridd =mysqli_query($con, "SELECT COUNT(Id) AS countt, level AS Lebel from affiliateuser WHERE level = '$countuserlevel' GROUP BY level");
  </code></pre>