Codeigniter Database Library

The  Database librarycontains a series of helpful functions that make it easy for you to create and run
queries and process the result sets from those queries.

The first thing to note about the Database library in CodeIgniter is that it allows you to pass in simple
SQL queries. At the end of the day, many people who are new to CodeIgniter find this to be a great
comfort. Although some of the built - in Active Record patterns provide helpful shortcuts, just knowing
that you can bypass all of that and send in a complex query.

$sql = “select a.name, a.id, b.groupname
from persons a, groups b
where a.group_id = b.id
group by b.groupname, a.name”;
$Q = $this- > db- > query($sql); 

To loop over the result set of that query, you can use either the result()or result_array() methods,
depending on whether you like to process your results as an object or as an array.

$sql = “select a.name, a.id, b.groupname
from persons a, groups b
where a.group_id = b.id
group by b.groupname, a.name”;
$Q = $this- > db- > query($sql);
foreach ($Q- > result() as $row){
echo $row- > name;
echo $row- > id;
echo $row- > groupname;
}
//here’s the alternative approach, with result_array
foreach ($Q- > result_array() as $row){
echo $row[‘name’];
echo $row[‘id’];
echo $row[‘groupname’];
}

If you need a count of rows in a result set, use the num_rows() method:
$sql = “select a.name, a.id, b.groupname
from persons a, groups b
where a.group_id = b.id
group by b.groupname, a.name”;
$Q = $this- > db- > query($sql);
if ($Q- > num_rows()){
foreach ($Q- > result() as $row){
echo $row- > name;
echo $row- > id;
echo $row- > groupname;
}
}
Sometimes you may have a query that generates just one result row.