CodeIgniter Forums
Extracting data from a result() array of objects. - 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: Extracting data from a result() array of objects. (/thread-25576.html)



Extracting data from a result() array of objects. - El Forum - 12-16-2009

[eluser]behdesign[/eluser]
In the user guide and in various other sources, I've only ever seen foreach() loops being used to display a mysql result(). This works fine if there's only one object or row, but I want to create a page that deals with dozens of records collated from a mysql query. I know that the result() is an array of objects, but how do I structure my view to express the objects in the array?

I assume there's some form of loop that I can use, but various iterations of while() and nested foreach() have failed me. Can anyone help?

Thanks!


Extracting data from a result() array of objects. - El Forum - 12-16-2009

[eluser]jedd[/eluser]
If you're more comfortable with arrays, just use the [url="/user_guide/database/results.html"]result_array()[/url] function to extract your data.

If you're having trouble with converting the SQL output into something displayable - then you'll have to describe the nature of the data.


Extracting data from a result() array of objects. - El Forum - 12-17-2009

[eluser]intractve[/eluser]
There are two options in CI for multiple rows,
result() and result_array()

take the following as the case result

id value allowed
1 foo true
2 bar false
3 tasty true

in your controller the result set is got by
Code:
$query = $this->db->get('table');
$rows = $query->result();

//You can directly send this result set to your view
$data['rows'] = $rows;
// This is just for example but you can do this directly in the first step itself.
//call the view

$this->load->view('view',$data);

Now your view has the variable $rows

Then in your view you can do
Code:
<table>
<tbody>
&lt;? foreach($rows as $row): ?&gt;
<tr>
<td>&lt;?=$row->id?&gt;</td>
<td>&lt;?=$row->value?&gt;</td>
<td>&lt;?=$row->allowed?&gt;</td>
</tr>
&lt;? endforeach; ?&gt;
</tbody></table>

Will print out a table with the above values.

A guide for the alternate syntax used above is here
PHP Alternate Syntax

Hope this helps.