Reputation: 25356
PDO apparently has no means to count the number of rows returned from a select query (mysqli
has the num_rows
variable).
Is there a way to do this, short of using count($results->fetchAll())
?
Upvotes: 13
Views: 39115
Reputation: 441
The Easiest
$stmt = $datalink->query('SELECT * FROM projects');
$rows = $stmt->fetchAll();
$num_rows = count($rows);
echo $num_rows ;
Upvotes: -2
Reputation: 157940
Although PDO apparently has all means to count the number of rows returned from a select query for mysql, what is more important is that there is no use for such a function in the first place.
Every time you have an idea to use rowCount() for a SELECT query, it would be either superfluous or even harmful. See PDO rowCount():
Upvotes: 4
Reputation: 9
Another option that may be closer to the num_rows
variable in mysqli
and the corresponding C API function mysql_num_rows()
. Is to use the MySQL function FOUND_ROWS()
that returns the same information without having to count all the records in the result again.
Example:
$pdoDB->query('SELECT FOUND_ROWS()')->fetchColumn()
Upvotes: 0
Reputation: 401172
According to the manual, there is a PDOStatement->rowCount
method ; but it shouldn't be used (quoting) :
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.
If you already have a recordset, and want to know how many lines are in it, you'll have to fetch the data, using one of the fetch*
methods ; and use count -- like you suggested.
Upvotes: 12