Whenever I am working with PHP MySQLi recordsets, I have always worked with the returned data using the standard while
loop to iterate over the recordset. Recently, however, I started wondering if there is a way to use a for
loop instead. This would be handy in situations where you want to limit the number of results returned.
Here is an example of using the while
loop:
//Prepare a query that will produce a reverse-order recordset
$sql = "SELECT * FROM tblNames ORDER BY numberID DESC";
$recordset = $conn -> query($sql);
//Count the number of contacts added to the list
$contactCount = 0;
while($row = $recordset -> fetch_assoc())
{
//If the list has reached its maximum number (5), end the display loop
if($contactCount >= 5)
{
break;
}
$contactList .= $row["name"] . "<br>";
//Increment the number of contacts added to the list
$contactCount ++;
}
//Use '$contactList' somewhere....
echo($contactList);
While this definitely works, there must be a better way to end the loop after a specified number of iterations. Is it easier to use a for
loop in a situation like this? If so, how?