Select multiple samples in pdo

The problem is that the output result for my total number of rows is not displayed. My actual code is:

<?
$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 it doesn't work, did I miss something?

+4
source share
1 answer

You can use ->nextRowset()to access the following data (as in the case of counting). First get (fetch) the rows you want. Then get a counter:

<?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;
    }
}
?>
+3
source

Source: https://habr.com/ru/post/1651636/


All Articles