doure8758 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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?



  • ¥15 有人能看一下我宿舍管理系统的报修功能该怎么改啊?链表那里总是越界
  • ¥15 cs loadimage运行不了,easyx也下了,没有用
  • ¥15 r包runway详细安装教程
  • ¥15 Html中读取Json文件中数据并制作表格
  • ¥15 谁有RH342练习环境
  • ¥15 STM32F407 DMA中断问题
  • ¥15 uniapp连接阿里云无法发布消息和订阅
  • ¥25 麦当劳点餐系统代码纠错
  • ¥15 轮班监督委员会问题。
  • ¥20 关于变压器的具体案例分析