Is there a way to get the number of records from a query with Zend-framework?

MichaelICE picture MichaelICE · Jun 11, 2009 · Viewed 8.3k times · Source

Given my generic select below, is there a way to get the number of records returned from a query with Zend Framework? $row++ in a loop is not acceptable for my solution as I am using paging (though its not in my sample).

I also DO NOT want to add another query with "Count(*)".

$query = "Select * from Users where active = 1";
$stmt = $db->query($query);

$noOfRows = ???;

while ($row = $stmt->fetch())
{

  // processing
}

Answer

Justin picture Justin · Jun 12, 2009

It still requires another query, but with MySQL there is a SELECT parameter SQL_CALC_FOUND_ROWS - it stores a value in your connection that you can then SELECT FOUND_ROWS()

Note - the performance of your initial query will go down, because the limit will be processed later, but it may be faster than a separate COUNT().

FOUND_ROWS()

$query = "Select SQL_CALC_FOUND_ROWS * from Users where active = 1 limit 20";
$stmt = $db->query($query);

while ($row = $stmt->fetch())
{

  // processing
}

$count = $db->fetchOne('SELECT FOUND_ROWS()');