[英]PHP Use for loop to iterate over MySQLi recordset
每當我使用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
循環會更容易嗎? 如果是這樣,怎么辦?
您可以在查詢中使用LIMIT
。 例如:
SELECT * FROM tblNames ORDER BY numberID DESC LIMIT 15
這樣,您不必擔心如果查詢返回的結果少於15個會發生什么。
當我寫這個問題時,我突然決定我上一次嘗試,但是使用的方式與以前不同。 我一直被困在尋找一種有效/安全的方法來告訴記錄集何時為空(當自定義最大數量大於記錄數量且沒有記錄時,就會遇到問題)。
//Execute the SQL query (reverse order), and store the results in a recordset
$sql = "SELECT * FROM tblNames ORDER BY numberID DESC";
$recordset = $conn -> query($sql);
//Use a 'for' loop to iterate over the recordset
for($i = 0; $i < 15; $i++)
{
//If there is another row in the recordset, add the column value to the list
if($row = $recordset -> fetch_assoc())
{
$contactList .= $row["name"] . "<br>";
}
else
{
//Break from the loop when there are no more records (used if the
// given maximum number was actually greater than the number of records)
break;
}
}
echo($contactList);
據我所知,這是遍歷一組設置/自定義記錄然后停止的更好的方法。 它還將安全地捕獲記錄集的末尾(假設在截止編號之前已到達記錄集的末尾),並結束循環。
編輯
正如上面的HenryTK的答案所指出的那樣,如果您可以控制查詢,則最好的方法是使用LIMIT
SQL語句。 但是,如果您僅能訪問記錄集,我仍然認為for
循環將節省時間。 (盡管我不確定何時會發生)。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.