【问题标题】:PHP Use for loop to iterate over MySQLi recordsetPHP 使用 for 循环遍历 MySQLi 记录集
【发布时间】: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


    【解决方案1】:

    您可以在查询中使用LIMIT。例如:

    SELECT * FROM tblNames ORDER BY numberID DESC LIMIT 15
    

    这样您就不必担心如果您的查询返回的结果少于 15 个会发生什么。

    【讨论】:

    • 哎呀!我早该想到的!我花了一段时间弄清楚如何在 PHP 中反转数组,然后才意识到我可以用 MySQLi 做到这一点。我不知道为什么我没想过要调查这个!谢谢!
    【解决方案2】:

    当我写这个问题时,我突然决定我会尝试最后一次,但方式与以前不同。我一直在寻找一种有效/安全的方法来判断记录集何时为空(当自定义最大数量大于记录数以及没有记录时遇到问题)。


    //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 循环将节省时间。 (虽然我不确定什么时候会发生)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-07-09
      • 2020-06-17
      • 1970-01-01
      • 2019-04-27
      • 2020-11-17
      相关资源
      最近更新 更多