Alaa Moneam
Alaa Moneam

Reputation: 527

how to get the count of row values in php pdo

There are many conflicting statements around, what is the best way to row count using PDO in PHP? Before using PDO I just simply used mysql_num_rows.

fetchAll is something I won't want as I may sometimes be dealing with large datasets, so not good for my use.

Any suggestions?

Upvotes: 0

Views: 1757

Answers (2)

chapskev
chapskev

Reputation: 982

In Mysql $stmt->rowCount(); doesnt work. Try this

$nRows = $pdo->query('select count(*) from yourTable')->fetchColumn(); 
echo 'Number of rows is = '. $nRows;

Here is an excerpt from a comment and answer regarding the same. Check it out its very resourceful.

mysql_num_rows() worked is because it was internally fetching all the rows to give you that information, even if it didn't seem like it to you. Refer to this anwere

So in PDO, your options are:

  1. Use MySQL's FOUND_ROWS() function.
  2. Use PDO's fetch_all() function to fetch all the rows into an array, then use count() on it.
  3. Do an extra query to SELECT COUNT(*),

https://stackoverflow.com/a/883523/2536812

Upvotes: 3

Bobot
Bobot

Reputation: 1118

Directly out form PHP Manual about PDO Statements

$stmt->rowCount();

The $stmtvalue is for exemple the return of a prepare :

$stmt = $pdo->prepare('MY PREPARED SQL QUERY');

Upvotes: 0

Related Questions