You can do this fairly easily by ordering your query by group_id
and then keeping track of when it changes. Something like this:
$query = "SELECT * FROM table ORDER BY group_id";
$results = $mysqli->query($query);
$lastGroup = 0;
while ( $row = $results->fetch_assoc() )
{
if ( $row['group_id'] != $lastGroup )
{
// If there is already a div open we need to close it, so if
// last group > 0 then a div has been opened.
echo ($lastGroup > 0 ? '</div>' : '') . '<div class="group' . $row['group_id'] . '">';
}
$lastGroup = $row['group_id'];
echo $row['username'] . '<br>';
}
// close the last open div
echo '</div>';
Alternatively you can use the MySQL GROUP_CONCAT
function to get back all the usernames in a group. Use this:
$query = "SELECT group_id,
GROUP_CONCAT(username) as users
FROM table
GROUP BY group_id";
$results = $mysqli->query($query);
while ( $row = $results->fetch_assoc() )
{
echo '<div class="group' . $row['group_id'] . '">' . $row['users'] . '</div>';
}