4

The problem is the output result for my total number of rows don't show up. My actual code:

<?
$stmt = $dbh->prepare("SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE mark=0 ORDER BY id ASC LIMIT 0, 15; SELECT FOUND_ROWS() as total;");
$stmt->execute();
if ($stmt->rowCount() > 0)
{
?>
<span>Number or rows: <? echo $stmt->total; ?></span>
<?
while($result = $stmt->fetch(PDO::FETCH_OBJ))
{
<?=$result->id;?>
<?=$result->user;?>
}
?>

What could be the reason why is not working, did I miss something?

Kevin
  • 41,694
  • 12
  • 53
  • 70
John
  • 323
  • 1
  • 4
  • 13

1 Answers1

5

You can use ->nextRowset() to access the next data (which in case the count). First get (fetch) the desired rows. Then get the count:

<?php
$stmt = $dbh->prepare("
    SELECT SQL_CALC_FOUND_ROWS * FROM table WHERE mark=0 ORDER BY id ASC LIMIT 0, 15; 
    SELECT FOUND_ROWS() as total;
");

$stmt->execute();

$values = $stmt->fetchAll(PDO::FETCH_OBJ);

$stmt->nextRowset(); // shift to the total

$count = $stmt->fetchColumn(); // get the total

?>

<span>Number of rows: <? echo $count; ?></span>

<?php
if($count > 0) {
    foreach($values as $v) {
        // iterate fetched rows
        echo $v->id;
    }
}
?>
Kevin
  • 41,694
  • 12
  • 53
  • 70