CodeIgniter Forums
foreach need? - Printable Version

+- CodeIgniter Forums (https://forum.codeigniter.com)
+-- Forum: Archived Discussions (https://forum.codeigniter.com/forum-20.html)
+--- Forum: Archived Development & Programming (https://forum.codeigniter.com/forum-23.html)
+--- Thread: foreach need? (/thread-27351.html)



foreach need? - El Forum - 02-08-2010

[eluser]rich.a.coy[/eluser]
Hi,

If I know I'm only pulling and displaying 1 record do I still need the "foreach"? I played around trying to remove it but it did not seem to work. I know this works but it seems like extra code.

Code:
<?php if(isset($user)) : foreach($user as $me) : ?>
    <?php echo $me->photo_url; ?>
    <?php echo $me->fname; ?>
<?php endforeach; ?>
<?php endif; ?>

Thanks.


foreach need? - El Forum - 02-08-2010

[eluser]richzilla[/eluser]
if in you're model, you're returning a
Code:
result()
value, then yes you do. If you're returning a
Code:
row()
value, then you don't. A solution would be to count the results at the model end, and return either a result() or row() depending on the outcome.


foreach need? - El Forum - 02-08-2010

[eluser]rich.a.coy[/eluser]
Ahh! In this case I know it's only one because I set a limit of one in the query and I'm looking up a unique user_id.

Thanks!


foreach need? - El Forum - 02-08-2010

[eluser]richthegeek[/eluser]
result() returns an array you can use standard array indexing to get individual rows, eg $result[0];


foreach need? - El Forum - 02-08-2010

[eluser]John_Betong[/eluser]
[quote author="rich.a.coy" date="1265664691"]Ahh! In this case I know it's only one because I set a limit of one in the query and I'm looking up a unique user_id.

Thanks![/quote]

From the User Manual:
Code:
row()

This function returns a single result row. If your query has more than one row, it returns only the first row. The result is returned as an object. Here's a usage example:

$query = $this->db->query("YOUR QUERY");

if ($query->num_rows() > 0)
{
   $row = $query->row();

   echo $row->title;
   echo $row->name;
   echo $row->body;
}
If you want a specific row returned you can submit the row number as a digit in the first parameter:

$row = $query->row(5);
row_array()