We’re trying to put a while inside a while loop.
The first while is run through and the results are displayed in a list (139, 140, 141).
The list for the second while only displays one value (1ste troop).
These are the results:
139
1ste troop
140
141
So it seems that the second while is only executed once.
What can I do to fix this?
echo "<ul>";
while($user = $allUsersintroops->fetch_assoc())
{
if($user['userid'] == $_SESSION['userid'])
{
echo "<li>" . $user['troopid']. " </li>";
while ($mytroops = $alltroops->fetch_assoc())
{
if($user['troopid'] == $mytroops['troopid'])
{
echo "<li>" . $mytroops['description']. " </li>";
}
}
}
}
echo "</ul>";
The inner loop stops once
fetch_assocreturns false… but that indicates the end of all found results and it doesn’t have any rows left for the next iteration.You should collect all the rows from
$alltroopsinto an array once, then iterate over that:Additionally, you should consider adding some filtering to your
$allUsersintroopsquery, because you are only using a part of the the returned rows, which means the rest of the rows are sent from the DB to your code for no reason, wasting time and bandwidth.