Php 查找while的最后一个循环($stmt->;fetch())

Php 查找while的最后一个循环($stmt->;fetch()),php,mysqli,while-loop,prepared-statement,Php,Mysqli,While Loop,Prepared Statement,是否有可能找到以下内容的最后一个循环是什么时候: $stmt = $connection->stmt_init(); if ($stmt->prepare("SELECT `ProductId` FROM Products")) { $stmt->execute(); $stmt->bind_result($product_id); while($stmt->fetch()) { if ($lastloop)

是否有可能找到以下内容的最后一个循环是什么时候:

$stmt = $connection->stmt_init();

if ($stmt->prepare("SELECT `ProductId` FROM Products"))
{
    $stmt->execute();
    $stmt->bind_result($product_id);

    while($stmt->fetch())
    {
       if ($lastloop)
       {
          echo 'The last id is -> ';
       }

       echo $product_id.'<br />';
    }
}
$stmt=$connection->stmt_init();
如果($stmt->prepare(“从产品中选择'ProductId'))
{
$stmt->execute();
$stmt->bind\u result($product\u id);
而($stmt->fetch())
{
如果($lastloop)
{
回显“最后一个id为->”;
}
echo$product_id.“
”; } }
我想输出如下内容:

1
2

9

最后一个id是->10

您可以保持计数并与行数进行比较

$stmt->store_result();
$rows = $stmt->num_rows;
$count = 1;
while( $stmt->fetch() ) {
    if( $count == $rows ) {
        echo 'The last id is -> ';
    }
    $count ++;
    echo $product_id . '<br />';
}
$stmt->store_result();
$rows=$stmt->num\u行;
$count=1;
而($stmt->fetch()){
如果($count==$rows){
回显“最后一个id为->”;
}
$count++;
echo$product_id.“
”; }
  • 只有在
    $stmt->store_result()
    结果集并持续计算活动行偏移量时,才可以使用,但。存储结果对于大型集合是不可行的
  • 使用
    从Products中选择SQL\u CALC\u FOUND\u ROWS ProductId如中所示。然后使用
    FOUND_ROWS()
    了解行号,而不首先存储结果集。需要一个额外的查询。。。这是一个很小的代价

  • 这就是所有可行且简单的解决方案。

    这不起作用。编辑它确实需要一个$stmt->store_result();编辑。对不起,我更熟悉PDO,它对solotuion 1的作用稍有不同。如果我在我的查询中得到了限制100,将被视为一个大集合吗?@zPuls3如果您有
    TEXT/BLOB
    列,其中包含KBs/MBs的数据,并且您没有
    SELECT*
    。。。它是。如果您只选择特定的小列,如此处所示。。。这不只是一个额外的评论。如果
    选择合理范围内的特定小列。。。最好总是存储,因为这限制了到服务器的往返。否则,对于每个
    获取
    。。。需要与服务器进行新的通信。这对大的有好处,但对小的没有好处。