Ian
Ian

Reputation: 25356

PHP PDO - Num Rows

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

Answers (4)

The Naga Tanker
The Naga Tanker

Reputation: 441

The Easiest

  $stmt = $datalink->query('SELECT * FROM projects');
  $rows = $stmt->fetchAll();
  $num_rows = count($rows);
  echo $num_rows ;

Upvotes: -2

Your Common Sense
Your Common Sense

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():

  • in case you have the data selected already, this function is superfluous as you simply can count the data
  • in case you want to use this function to get the count only, it would harmful, as you should never select data only to count it. Select only count, using SELECT count(*) instead.

Upvotes: 4

Angelstam
Angelstam

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

Pascal MARTIN
Pascal MARTIN

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 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.


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

Related Questions