Professional CodeIgniter, Thomas Myer

Chapter 3: A 10,000 - Foot View of CodeIgniter
56

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'];
}

There ' s really no discernible difference from a performance standpoint, but some developers prefer one
over the other. It ' s your choice, really.

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. In that case, use
row()

or
row_array()

(again, depending on your preference) to process that result set.
$sql = "select a.name, a.id, b.groupname
from persons a, groups b
where a.group_id = b.id
limit 1";
c03.indd 56
c03.indd 56
6/10/08 5:33:49 PM
6/10/08 5:33:49 PM


Другие страницы

 
Cкачать книги бесплатно без регистрации в электронном виде (pdf, chm, txt).Вы можете читать книги онлайн на нашем сайте литературного портала книг.Большая подборка учебников, пособий, интересных книг.Электронные книги на английском языке скачать бесплатно без смс.

OK

Loading...
...
Закрыть