Question

I am using Zend fetch method to fetch huge number of records from database for creating reports.Since fetchAll is costly as compared to fetch i am using it.And if its the last row i need to add some additinoal logic.So my question is that is there a way to check if next record exists or not inside the while loop. I am using it like the following

//$select is the select query
$objDb      = Zend_Registry::get('db');
$objAchQry = $objDb->query($select);
while($arrResult = $objAchQry->fetch()) {
  //Do something

  //I need to do something here if its the last record like
  /*
  if($last_rec)
    do something
  */
}

Is there a way to check if the current one is last record or if any other record exists. I know to do it by taking count of records and incrementing a counter inside the loop.But i dont need it.Any solutions.?

Was it helpful?

Solution

"is there a way to check if next record exists" The condition on your while loop does exactly just that. The loop won't execute any more if no more rows exist to fetch.

Think of it this way:

while($arrResult = $objAchQry->fetch()) {

  //Do something

}

// Now I'm just after the last record
/*
do something
*/

If you really need to do something before the last row is processed, you could modify your code to

$total_records = // get total no of rows
$counter = 0;
while($arrResult = $objAchQry->current()) {
  //Do something
  $counter ++;

  //I need to do something here if its the last record like

  if( ! $bojAchQry->next()) {

    // The row currently being processed is the last one.

  } else {

    break;
  }
}

OTHER TIPS

One way - You can track with counter,

$total_records = // get total no of rows
$counter = 0;
while($arrResult = $objAchQry->fetch()) {
  //Do something
  $counter ++;

  //I need to do something here if its the last record like

  if($counter == $total_records  ) // this iteration will be the last one.
   //do something

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top