Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
}
like image 761
MichaelICE Avatar asked Jun 11 '09 20:06

MichaelICE


1 Answers

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()');
like image 58
Justin Avatar answered Sep 23 '22 02:09

Justin