tags:

views:

363

answers:

3

Hello all,

I have this:

$dbh = new PDO("odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=$mdbFilename", $username, $password);

$sql = "SELECT * FROM this_table";

$stmt = $dbh->query($sql);

//num of rows?

How do I get the number of rows returned from that SELECT statement?

Thanks all

+1  A: 

SELECT count(*) FROM this_table is an option...

Regarding rowCount:

PDOStatement::rowCount() returns the number of rows affected by the last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.

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.

Leniel Macaferi
I don't want to run another query.
Abs
This link may be of some help: http://php.net/manual/en/pdostatement.rowcount.php
Leniel Macaferi
A: 

I have found a solution, using fetchAll and then using count on this array - which is what MySQL does anyway internally, a bit inefficient but it works for me.

$q = $db->query("SELECT ...");
$rows = $q->fetchAll();
$rowCount = count($rows);

From another question Chad provided this insight:

It seems as though the only reason this was possible with MySQL is because it internally fetched all the result rows and buffered them, to be able to give you this information. See mysql_unbuffered_query(). If you use that function instead of mysql_query(), the mysql_num_rows() function will not work. If you really need to know the number of rows while using PDO, you can fetch all of the rows from PDO into an array and then use count().

Hope this is useful to someone.

Abs
+2  A: 

$stmt->rowCount();

Ronald D. Willis
No, this only works for INSERT, UPDATE and DELETE. It shows the rows effected, not the rows returned by a select statement.
Abs