【发布时间】:2015-09-26 14:58:10
【问题描述】:
每当我使用 PHP MySQLi 记录集时,我总是使用标准的 while 循环来遍历记录集来处理返回的数据。然而,最近,我开始想知道是否有办法使用for 循环。这在您想要限制返回的结果数量的情况下会很方便。
以下是使用while 循环的示例:
//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);
虽然这绝对有效,但必须有更好的方法在指定的迭代次数后结束循环。在这种情况下使用for 循环是否更容易?如果有,怎么做?
【问题讨论】:
标签: php database for-loop mysqli recordset