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


Loop runs 9 times and gains info gradually

我试图从数据库中拉入一些数据,循环的行为很奇怪。这是

我代码:

<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>

您可以看到这里的输出。

基本上,存在重复条目的模式,并且有些条目甚至在列表进一步向下时才出现。

感谢您的帮助

我现在改变了一点:

<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>

您需要在迭代$rows之前结束while循环。让while循环填充数组,然后遍历它。就像现在一样,你在迭代$rows数组的同时也在填充它。

那么这里发生的是:

Name 1被找到并添加到数组中——> array有1个元素。

找到

Name 2并添加到数组--> array有2个元素。输出两个元素

等。等。

修复:

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>";
  }
}