Working with result sets

LEAP returns all queried data in a result set. The returned result set is essentially a wrapper class around a PHP array with a set of convenience functions.

The mostly commonly used convenience function is DB_ResultSet::count(). This function maintains the number of records stored in the result set. Unlike some other count() functions in PHP, the count() in this class does not have to recalculate every time it is called. It is called like so:

1 <?php
2 $results->count();

Another commonly used convenience function is DB_ResultSet::is_loaded(). It returns whether any records were fetched from the database. To call this function, it is called like so:

1 <?php
2 if ($results->is_loaded()) {
3 	// do something
4 }

LEAP’s result set can also act like an array in that it can be access like one and looped through as one. There are two ways data can be access:

Method #1

1 <?php
2 $record = $results->fetch(0);

Method #2

1 <?php
2 $record = $results[0];

To loop through the results, use the foreach loop.

1 <?php
2 foreach ($results as $record) {
3     // do something
4 }

The results can also be looped through using the while loop:

1 <?php
2 while ($record = $results->fetch()) {
3     // do something
4 }

Likewise, the results can be looped through using the traditional for loop:

1 <?php
2 for ($i = 0; $i < $results->count(); $i++) {
3     $record = $results[$i];
4     // do something
5 }

An added feature to LEAP’s result set is that you can also get at a particular column’s value in the current row by using the DB_ResultSet::get(). A default value can also be set should no value be found for the specified column.

1 <?php
2 $value = $results->get('FirstName', '');

If you prefer to work with the result set as an array, you can call as_array() like so:

1 <?php
2 $records = $results->as_array();

Similarly, you can call as_csv() to dump a result set into LEAP’s CSV class, which can be used to export query data.

1 <?php
2 $csv = $results->as_csv(array(
3    'file_name' => 'data.csv',
4    'default_headers' => TRUE,
5    'delimiter' => ',',
6    'enclosure' => '"',
7    'eol' => "\n",
8 ));
9 $csv->output(TRUE);