循环运行9次并逐渐获得信息

I'm trying to pull in some data from my database, and the loop is behaving strangely. this is

my code:

<code>
  $query = "SELECT DISTINCT * FROM users WHERE username LIKE '%$search%'";

  $resultpage = "";

  $result = mysqli_query($con,$query);

  $rows = array();

  $resultpage = "<table class='table table-striped table-hover><tbody><tr><td>Search Results</td></tr>";

  while($row = mysqli_fetch_assoc($result)) {
    $rows[] = $row;

    foreach($rows as $row) {
      foreach($rows as $field => $value) {          
        array_unique($rows);
        $resultpage .= "<tr><td><a href='user?id=".$value["id"]."'>".$value["username"]."</a></tr></td>";
      }
    }      
  }
</code>

You can see what is output here.

Basically, there are patterns of duplicate entries, and some of the entries don't even appear until you get farther down the list.

Thanks for any help

I am chancing a bit now:

<code>
  $query = "SELECT DISTINCT * FROM users WHERE username LIKE '%$search%'";

  $rs = mysqli_query($con,$query);

  echo "<table class='table table-striped table-hover'><tbody><tr><td>Search Results</td></tr>";

  while($row = mysqli_fetch_assoc($rs)) {    
    $id = $row["id"];
    $username = html_encode($row["username"]);
    echo "<tr><td><a href='user.php?id=$id'>$username</a></td></tr>";
  }

  echo "</table>";
</code>

You need to end your while loop before you iterate through $rows. Let the while loop populate the array and then iterate through it. As it is right now, you're iterating through the $rows array while you are also populating it.

So what's happening here is:

Name 1 is found and added to array --> Array has 1 element. This element is printed.

Name 2 is found and added to array --> Array has 2 elements. Both elements are printed.

Etc. etc.

Here's the fix:

while($row = mysqli_fetch_assoc($result)) {
  $rows[] = $row;
}

foreach($rows as $row) {
  foreach($row as $field => $value) {          
    array_unique($row);
    $resultpage .= "<tr><td><a href='user?id=".$value["id"]."'>".$value["username"]."</a></tr></td>";
  }
}