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?
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 aSELECT
statement.
Instead, usePDO::query()
to issue aSELECT COUNT(*)
statement with the same predicates as your intendedSELECT
statement, then usePDOStatement::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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With