Search code examples
phpmysqldatabasedrupaldrupal-7

with limit(20) it runs only the first 20 values of DB


In this lines of code it selects only the first 20 but i want the first time select the first 20 and then the other and other and so on :'( How I can solve this problem?

function something_cron()
  $query = db_select('watchdog', 'wa')
    ->extend('PagerDefault')
    ->orderBy('wid')
    ->fields('wa', array('variables', 'type', 'severity',
  'message', 'wid', 'timestamp'))
    ->limit(20);
  $result = $query->execute();

  // Loop through each item and add to $row.
  foreach ($result as $row) {
    someother();
  }

I also want to avoid this PagerDefault but i cannot..


Solution

  • Firstly, you don't need PagerDefault if you're not displaying a pager. You can use orderBy and range without it.

    If I'm understanding your post, everytime cron is run, you want the first 20 rows of the watchdog table. If this is the case, I would suggest keeping track of the last watchdog id (wid) you got from the table and use that for each subsequent run. Something like:

    $wid = variable_get('my_last_wid', 0);
    
    $result = db_select('watchdog')
      ->fields('watchdog', array('variables', 'type', 'severity', 'message', 'wid', 'timestamp'))
      ->condition('wid', $wid, '>')
      ->orderBy('wid')
      ->range(0, 20)
      ->execute();
    
    foreach ($result as $watchdog) {
      // do whatever you need to do
    }
    
    if (!empty($watchdog)) {
      variable_set('my_last_wid', $watchdog->wid);
    }