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

时间:2013-07-19 13:57:20

标签: 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)
       {
          echo 'The last id is -> ';
       }

       echo $product_id.'<br />';
    }
}

我想输出类似的东西:

1
2
...
9
最后一个ID是 - &gt; 10

2 个答案:

答案 0 :(得分:1)

您可以继续计算并与行数进行比较

$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 />';
}

答案 1 :(得分:1)

  1. 您可以使用$stmt->num_rows^,但仅在$stmt->store_result()结果集时使用并继续计算有效行偏移量。 存储结果对于大型集合不可行。
  2. this answer here^中使用 SELECT SQL_CALC_FOUND_ROWS ProductId FROM Products; 。然后使用FOUND_ROWS()来了解行号最初没有存储结果集需要一个额外的查询...这是一个很小的代价。
  3. 这就是你所拥有的可行且简单的解决方案。