You may use the table method on the DB service to begin a query. The table method returns a query builder instance for the given table, allowing you to chain more constraints onto the query and then finally get the results using any of the below methods:
Use the fetchRow method to get a single row. By default the row is a php standard object, pass true as the first parameter
for the row to be associate array.
$users = $this->db->table('users')->where('id', '=', 5)->fetchRow();
$users = $this->db->table('users')->where('id', '=', 5)->fetchRow(true);
Use the fetchObject method to get a single row. Row is a php object of the type you pass it.
$users = $this->db->table('users')->where('id', '=', 5)->fetchObject(new User());
Use the fetchRows method to get an array of all rows. By default the rows are returned as php objects, pass true as the first parameter
for the rows to be associate array.
$users = $this->db->table('users')->fetchRows();
$users = $this->db->table('users')->fetchRows(true);
Use the fetchObjects method to get an array of all rows. Each row is a php object of the type you pass it.
$users = $this->db->table('users')->fetchObjects(new User());
You can also retrieve the resulting array as an associtive array with a column as the key.
$users = $this->db->table('users')->select(['id', 'email', 'name'])->fetchRowsWithColumnKey('id');
If you would like to retrieve a Collection containing the values of a single column, you may use the fetchAllColumn method. In this example, we'll retrieve a Collection of titles:
$titles = $this->db->table('users')->select('title')->fetchAllColumn();
If you don't need an entire row, you may extract a single value from a record using the fetchValue method. This method will return the value of the column directly:
$email = $this->db->table('users')->select('email')->fetchValue();
You may retrieve a list as a key value pair using the fetchKeyValuePair method.
$options = $this->db->table('options')->fetchKeyValuePair('name', 'value');
The query builder also provides a variety of aggregate methods such as count, max, min,
avg, and sum. You may call any of these methods after constructing your query:
$users = $this->db->table('users')->count();
$price = $this->db->table('orders')->max('price');
You may combine these methods with other clauses:
$price = $this->db->table('orders')
->where('finalized', 1)
->avg('price');