回声只有x次

I have a while loop that will echo all the results from a database. It goes something like this:

while ($row2 = mysqli_fetch_array($result2)) {
    echo  $row2['fname']. "<br>";   
}

Problem is, I only want it to echo it out max 5 times, and if there's more than 5 people in the result I want it to show the five first results and a "Click here to view all members" button instead. I've tried searching for it, but I'm not getting any good results mostly due to poor search queries

Thanks for the downvotes and all the great answers. Sorry if I failed to conform to how one of these questions should look.

Declare a counter, then exit:

$count = 0;
while ($row2 = mysqli_fetch_array($result2)) {
    echo  $row2['fname']. "<br>";
    $count++;
    if(5 == $count) {
         break;
    }
}

break

OR, you could add a LIMIT clause to your query.

Simply add a counter variable and exit the loop if it reaches 5. Consider the following code:

$counter = 0;
while ($row2 = mysqli_fetch_array($result2)) {
    if(++$counter <= 5){
        echo  $row2['fname']. "<br>";
    }else{
        // Echo your "Click here to view all members" button
        break;
    }
}

Set a counter with a if/else statement inside your while loop.

$x=0;
while ($row2 = mysqli_fetch_array($result2)) {
    if(x <= 4){
    echo  $row2['fname']. "<br>"; 
    x++; 
    }else{
       //do something else, or
       break;
    } 
}