You are here

public function FeedsSQLFetcher::fetch in Feeds SQL 7

Implements FeedsFetcher::fetch().

File

plugins/FeedsSQLFetcher.inc, line 16
Fetches data from an SQL database.

Class

FeedsSQLFetcher
Fetches data via pdo connection.

Code

public function fetch(FeedsSource $source) {
  $results = array();
  $source_config = $source
    ->getConfigFor($this);
  $source_config['query'] = trim($source_config['query']);
  $query = token_replace($source_config['query']);

  // Make sure there is only one query
  if ($end = strpos($query, ';')) {
    $query = substr($query, 0, $end + 1);
  }

  // Verify the query is a SELECT statement
  $select = strtoupper(substr($query, 0, 6));
  if ($select != 'SELECT') {
    drupal_set_message(t('SQL query has to be of the form "SELECT field1, field2 FROM table WHERE conditions"'), 'error');
  }
  else {

    // Run the query on the selected database
    db_set_active($source_config['database']);
    $result = @db_query($query);
    foreach ($result as $record) {
      $results[] = $record;
    }

    // Switch back to the default database
    db_set_active();
  }
  return new FeedsFetcherResult($results);
}