Generating Query Results

There are several ways to generate query results:

Result Arrays

getResult()

This method returns the query result as an array of objects, oran empty array on failure. Typically you’ll use this in a foreachloop, like this:

  1. $query = $db->query("YOUR QUERY");
  2.  
  3. foreach ($query->getResult() as $row)
  4. {
  5. echo $row->title;
  6. echo $row->name;
  7. echo $row->body;
  8. }

The above method is an alias of getResultObject().

You can pass in the string ‘array’ if you wish to get your resultsas an array of arrays:

  1. $query = $db->query("YOUR QUERY");
  2.  
  3. foreach ($query->getResult('array') as $row)
  4. {
  5. echo $row['title'];
  6. echo $row['name'];
  7. echo $row['body'];
  8. }

The above usage is an alias of getResultArray().

You can also pass a string to getResult() which represents a class toinstantiate for each result object

  1. $query = $db->query("SELECT * FROM users;");
  2.  
  3. foreach ($query->getResult('User') as $user)
  4. {
  5. echo $user->name; // access attributes
  6. echo $user->reverseName(); // or methods defined on the 'User' class
  7. }

The above method is an alias of getCustomResultObject().

getResultArray()

This method returns the query result as a pure array, or an emptyarray when no result is produced. Typically you’ll use this in a foreachloop, like this:

  1. $query = $db->query("YOUR QUERY");
  2.  
  3. foreach ($query->getResultArray() as $row)
  4. {
  5. echo $row['title'];
  6. echo $row['name'];
  7. echo $row['body'];
  8. }

Result Rows

getRow()

This method returns a single result row. If your query has more thanone row, it returns only the first row. The result is returned as anobject. Here’s a usage example:

  1. $query = $db->query("YOUR QUERY");
  2.  
  3. $row = $query->getRow();
  4.  
  5. if (isset($row))
  6. {
  7. echo $row->title;
  8. echo $row->name;
  9. echo $row->body;
  10. }

If you want a specific row returned you can submit the row number as adigit in the first parameter:

  1. $row = $query->getRow(5);

You can also add a second String parameter, which is the name of a classto instantiate the row with:

  1. $query = $db->query("SELECT * FROM users LIMIT 1;");
  2. $row = $query->getRow(0, 'User');
  3.  
  4. echo $row->name; // access attributes
  5. echo $row->reverse_name(); // or methods defined on the 'User' class

getRowArray()

Identical to the above row() method, except it returns an array.Example:

  1. $query = $db->query("YOUR QUERY");
  2.  
  3. $row = $query->getRowArray();
  4.  
  5. if (isset($row))
  6. {
  7. echo $row['title'];
  8. echo $row['name'];
  9. echo $row['body'];
  10. }

If you want a specific row returned you can submit the row number as adigit in the first parameter:

  1. $row = $query->getRowArray(5);

In addition, you can walk forward/backwards/first/last through yourresults using these variations:

$row = $query->getFirstRow()
$row = $query->getLastRow()
$row = $query->getNextRow()
$row = $query->getPreviousRow()

By default they return an object unless you put the word “array” in theparameter:

$row = $query->getFirstRow(‘array’)
$row = $query->getLastRow(‘array’)
$row = $query->getNextRow(‘array’)
$row = $query->getPreviousRow(‘array’)

Note

All the methods above will load the whole result into memory(prefetching). Use getUnbufferedRow() for processing largeresult sets.

getUnbufferedRow()

This method returns a single result row without prefetching the wholeresult in memory as row() does. If your query has more than one row,it returns the current row and moves the internal data pointer ahead.

  1. $query = $db->query("YOUR QUERY");
  2.  
  3. while ($row = $query->getUnbufferedRow())
  4. {
  5. echo $row->title;
  6. echo $row->name;
  7. echo $row->body;
  8. }

You can optionally pass ‘object’ (default) or ‘array’ in order to specifythe returned value’s type:

  1. $query->getUnbufferedRow(); // object
  2. $query->getUnbufferedRow('object'); // object
  3. $query->getUnbufferedRow('array'); // associative array

Custom Result Objects

You can have the results returned as an instance of a custom class insteadof a stdClass or array, as the getResult() and getResultArray()methods allow. If the class is not already loaded into memory, the Autoloaderwill attempt to load it. The object will have all values returned from thedatabase set as properties. If these have been declared and are non-publicthen you should provide a __set() method to allow them to be set.

Example:

  1. class User
  2. {
  3. public $id;
  4. public $email;
  5. public $username;
  6.  
  7. protected $last_login;
  8.  
  9. public function lastLogin($format)
  10. {
  11. return $this->lastLogin->format($format);
  12. }
  13.  
  14. public function __set($name, $value)
  15. {
  16. if ($name === 'lastLogin')
  17. {
  18. $this->lastLogin = DateTime::createFromFormat('U', $value);
  19. }
  20. }
  21.  
  22. public function __get($name)
  23. {
  24. if (isset($this->$name))
  25. {
  26. return $this->$name;
  27. }
  28. }
  29. }

In addition to the two methods listed below, the following methods also cantake a class name to return the results as: getFirstRow(), getLastRow(),getNextRow(), and getPreviousRow().

getCustomResultObject()

Returns the entire result set as an array of instances of the class requested.The only parameter is the name of the class to instantiate.

Example:

  1. $query = $db->query("YOUR QUERY");
  2.  
  3. $rows = $query->getCustomResultObject('User');
  4.  
  5. foreach ($rows as $row)
  6. {
  7. echo $row->id;
  8. echo $row->email;
  9. echo $row->last_login('Y-m-d');
  10. }

getCustomRowObject()

Returns a single row from your query results. The first parameter is the rownumber of the results. The second parameter is the class name to instantiate.

Example:

  1. $query = $db->query("YOUR QUERY");
  2.  
  3. $row = $query->getCustomRowObject(0, 'User');
  4.  
  5. if (isset($row))
  6. {
  7. echo $row->email; // access attributes
  8. echo $row->last_login('Y-m-d'); // access class methods
  9. }

You can also use the getRow() method in exactly the same way.

Example:

  1. $row = $query->getCustomRowObject(0, 'User');

Result Helper Methods

getFieldCount()

The number of FIELDS (columns) returned by the query. Make sure to callthe method using your query result object:

  1. $query = $db->query('SELECT * FROM my_table');
  2.  
  3. echo $query->getFieldCount();

getFieldNames()

Returns an array with the names of the FIELDS (columns) returned by the query.Make sure to call the method using your query result object:

  1. $query = $db->query('SELECT * FROM my_table');
  2.  
  3. echo $query->getFieldNames();

freeResult()

It frees the memory associated with the result and deletes the resultresource ID. Normally PHP frees its memory automatically at the end ofscript execution. However, if you are running a lot of queries in aparticular script you might want to free the result after each queryresult has been generated in order to cut down on memory consumption.

Example:

  1. $query = $thisdb->query('SELECT title FROM my_table');
  2.  
  3. foreach ($query->getResult() as $row)
  4. {
  5. echo $row->title;
  6. }
  7.  
  8. $query->freeResult(); // The $query result object will no longer be available
  9.  
  10. $query2 = $db->query('SELECT name FROM some_table');
  11.  
  12. $row = $query2->getRow();
  13. echo $row->name;
  14. $query2->freeResult(); // The $query2 result object will no longer be available

dataSeek()

This method sets the internal pointer for the next result row to befetched. It is only useful in combination with getUnbufferedRow().

It accepts a positive integer value, which defaults to 0 and returnsTRUE on success or FALSE on failure.

  1. $query = $db->query('SELECT `field_name` FROM `table_name`');
  2. $query->dataSeek(5); // Skip the first 5 rows
  3. $row = $query->getUnbufferedRow();

Note

Not all database drivers support this feature and will return FALSE.Most notably - you won’t be able to use it with PDO.

Class Reference

  • CodeIgniter\Database\BaseResult
getResult([$type = 'object'])
Parameters:
  • $type (string) – Type of requested results - array, object, or class name
Returns:

Array containing the fetched rows

Return type:

array

A wrapper for the getResultArray(), getResultObject()and getCustomResultObject() methods.

Usage: see Result Arrays.

getResultArray()
Returns:Array containing the fetched rows
Return type:array

Returns the query results as an array of rows, where eachrow is itself an associative array.

Usage: see Result Arrays.

getResultObject()
Returns:Array containing the fetched rows
Return type:array

Returns the query results as an array of rows, where eachrow is an object of type stdClass.

Usage: see Result Arrays.

getCustomResultObject($class_name)
Parameters:
  • $class_name (string) – Class name for the resulting rows
Returns:

Array containing the fetched rows

Return type:

array

Returns the query results as an array of rows, where eachrow is an instance of the specified class.

getRow([$n = 0[, $type = 'object']])
Parameters:
  • $n (int) – Index of the query results row to be returned
  • $type (string) – Type of the requested result - array, object, or class name
Returns:

The requested row or NULL if it doesn’t exist

Return type:

mixed

A wrapper for the getRowArray(), getRowObject() andgetCustomRowObject() methods.

Usage: see Result Rows.

getUnbufferedRow([$type = 'object'])
Parameters:
  • $type (string) – Type of the requested result - array, object, or class name
Returns:

Next row from the result set or NULL if it doesn’t exist

Return type:

mixed

Fetches the next result row and returns it in therequested form.

Usage: see Result Rows.

getRowArray([$n = 0])
Parameters:
  • $n (int) – Index of the query results row to be returned
Returns:

The requested row or NULL if it doesn’t exist

Return type:

array

Returns the requested result row as an associative array.

Usage: see Result Rows.

getRowObject([$n = 0])
Parameters:
  • $n (int) – Index of the query results row to be returned
Returns:

The requested row or NULL if it doesn’t exist

Return type:

stdClass

Returns the requested result row as an object of typestdClass.

Usage: see Result Rows.

getCustomRowObject($n, $type)
Parameters:
  • $n (int) – Index of the results row to return
  • $class_name (string) – Class name for the resulting row
Returns:

The requested row or NULL if it doesn’t exist

Return type:

$type

Returns the requested result row as an instance of therequested class.

dataSeek([$n = 0])
Parameters:
  • $n (int) – Index of the results row to be returned next
Returns:

TRUE on success, FALSE on failure

Return type:

bool

Moves the internal results row pointer to the desired offset.

Usage: see Result Helper Methods.

setRow($key[, $value = NULL])
Parameters:
  • $key (mixed) – Column name or array of key/value pairs
  • $value (mixed) – Value to assign to the column, $key is a single field name
Return type:

void

Assigns a value to a particular column.

getNextRow([$type = 'object'])
Parameters:
  • $type (string) – Type of the requested result - array, object, or class name
Returns:

Next row of result set, or NULL if it doesn’t exist

Return type:

mixed

Returns the next row from the result set.

getPreviousRow([$type = 'object'])
Parameters:
  • $type (string) – Type of the requested result - array, object, or class name
Returns:

Previous row of result set, or NULL if it doesn’t exist

Return type:

mixed

Returns the previous row from the result set.

getFirstRow([$type = 'object'])
Parameters:
  • $type (string) – Type of the requested result - array, object, or class name
Returns:

First row of result set, or NULL if it doesn’t exist

Return type:

mixed

Returns the first row from the result set.

getLastRow([$type = 'object'])
Parameters:
  • $type (string) – Type of the requested result - array, object, or class name
Returns:

Last row of result set, or NULL if it doesn’t exist

Return type:

mixed

Returns the last row from the result set.

getFieldCount()
Returns:Number of fields in the result set
Return type:int

Returns the number of fields in the result set.

Usage: see Result Helper Methods.

  • getFieldNames()
returns:Array of column names
rtype:array

Returns an array containing the field names in theresult set.

  1. - <code>getFieldData</code>()[](#getFieldData)
  2. -

Returns:Array containing field meta-dataReturn type:array

Generates an array of stdClass objects containingfield meta-data.

  1. - <code>freeResult</code>()[](#freeResult)
  2. -

Return type:void

Frees a result set.

Usage: see Result Helper Methods.