Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP's PDO loop returning all excluding first row

Tags:

php

pdo

symfony1

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?

like image 444
TomaszSobczak Avatar asked Feb 25 '23 19:02

TomaszSobczak


1 Answers

Quoting the documentation of PDOStatement->rowCount :

If the last SQL statement executed by the associated PDOStatement was a SELECT statement, some databases may return the number of rows returned by that statement.
However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.

and the note on Example #2 :

For most databases, PDOStatement::rowCount() does not return the number of rows affected by a SELECT statement.
Instead, use PDO::query() to issue a SELECT COUNT(*) statement with the same predicates as your intended SELECT statement, then use PDOStatement::fetchColumn() to retrieve the number of rows that will be returned.
Your application can then perform the correct action.

So, not really an answer to the why of your question, but I would say you should not use rowCount() for a select query ;-)


See also the notes on that documentation page ; for example, this one, which says (quoting) :

It appears that rowCount behavior is different on Mysql 5.0 vs 5.1.

And, with a query as simple as "SELECT 1" :

Mysql 5.0.45, PHP 5.2.5 returned 1
Mysql 5.1.30, PHP 5.1.6 returned 0

like image 145
Pascal MARTIN Avatar answered Feb 27 '23 08:02

Pascal MARTIN