doure8758 2015-07-08 15:25
浏览 46
已采纳

PHP使用for循环来迭代MySQLi记录集

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?

  • 写回答

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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址
  • ¥15 elmos524.33 eeprom的读写问题
  • ¥15 使用Java milo连接Kepserver服务端报错?
  • ¥15 用ADS设计一款的射频功率放大器
  • ¥15 怎么求交点连线的理论解?
  • ¥20 软件开发方法学习来了
  • ¥15 微信小程序商城如何实现多商户收款 平台分润抽成