开发者

Get Number of Rows from a Select statement

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 state开发者_开发知识库ment?

Thanks all


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜