2015-07-08 15:25
浏览 46


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)

    $contactList .= $row["name"] . "<br>";

    //Increment the number of contacts added to the list
    $contactCount ++;

//Use '$contactList' somewhere....

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?

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dopod0901 2015-07-08 15:38

    You can use LIMIT in the query. For example:

    SELECT * FROM tblNames ORDER BY numberID DESC LIMIT 15

    This way you don't have to worry about what happens if your query does return less than 15 results.

    解决 无用
    打赏 举报

相关推荐 更多相似问题