Search code examples
phpsymfony1pdo

PHP's PDO loop returning all excluding first row


Got problem with PDOStatement->fetch under symfony (v1.4.6) as while fetching records from statement first row is always excluded.

Code bellow:

<?php var_dump($stats->rowCount()); ?>
<?php var_dump(count($stats->fetchAll())); ?>

Produces:

int 14
int 13

And code bellow:

<?php $i = 0; ?>
<?php var_dump($stats->rowCount()); ?>
<?php while ($v = $stats->fetch()): ?>
    <?php var_dump(++$i); ?>

Produces:

int 14
int 1
int 2
int 3
int 4
int 5
int 6
int 7
int 8
int 9
int 10
int 11
int 12
int 13

Any ideas why row is excluded?


Solution

  • Problem SOLVED and it wasn't PDO related but Symfony related problem (one of the OutputDecorators i think but don't know sure yet)

    PDOStatement was valid and when looping through it with ->fetch inside controller everything was fine (14 records retrieved). After moving the same code to view first record was always excluded from results (and i think its related with that output decorators are using Iterator and ArrayAccess).

    Quick workaround for this issue is NOT using while loop but make usage of implemented Iterator and ArrayAccess so final code that works as expected (returns all rows) is using foreach

    <?php foreach ($stats as $v): ?>
        <?php //do stuff with record ?>
    <?php endforeach; ?>
    

    insted of while + ->fetch() loop

    <?php while ($v = $stats->fetch()): ?>
        <?php //1st record is missing here somehow ?>
    <?php endwhile; ?>