Generating Query Results¶
There are several ways to generate query results:
Result Arrays¶
findAll()
This method returns the query result as a pure array, or an empty array when no result is produced. Typically you’ll use this in a foreach loop, like this:
$query = $this->db->query("YOUR QUERY");
foreach ($query->findAll() as $row)
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
findOne()
This method returns an associative single array, or an empty array when no result is produced. Example:
$query = $this->db->query("YOUR QUERY");
$row = $query->findOne();
if (isset($row))
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
findRow()
This method returns an array, or an empty array when no result is produced. Example:
$query = $this->db->query("YOUR QUERY");
$row = $query->findRow();
if (isset($row))
{
echo $row['title'];
echo $row['name'];
echo $row['body'];
}
findObject()
This method returns an array object, or an empty array when no result is produced. Example:
$query = $this->db->query("YOUR QUERY");
$row = $query->findObject();
if (isset($row))
{
echo $row->title;
echo $row->name;
echo $row->body;
}
Result Helper Methods¶
count()
The number of rows returned by the query. Note: In this example, $query is the variable that the query result object is assigned to:
$query = $this->db->query('SELECT * FROM my_table');
echo $query->count();
Note
Not all database drivers have a native way of getting the total
number of rows for a result set. When this is the case, all of
the data is prefetched and count()
is
manually called on the
resulting array in order to achieve the same result.
field_count()
The number of FIELDS (columns) returned by the query.
$query = $this->db->query('SELECT * FROM my_table');
echo $query->field_count();
offset()
This method sets the internal pointer for the next result row to be fetched.
It accepts a positive integer value, which defaults to 0 and returns TRUE on success or FALSE on failure.
$query = $this->db->query('SELECT `field_name` FROM `table_name`');
$query->offset(5); // Skip the first 5 rows
$row = $query->findRow();
Note
Not all database drivers support this feature and will return FALSE. Most notably - you won’t be able to use it with PDO.