Displaying Array Data |
[eluser]NateL[/eluser]
I have some simple information coming out of my database, and displaying in an array called "$result" Code: <pre><?=print_r($result)?></pre> returns Code: <body> I know I can use a foreach statement to display multiple database results, but in this instance, I just need to access and display the Description. Seems fairly elementary to me, but I keep hitting an error ![]()
[eluser]davidbehler[/eluser]
What about something like this? Code: echo $result[0]->description;
[eluser]NateL[/eluser]
That works - but I feel like "$result[0]" is not very descriptive and could lead to confusion later on down the road. I will go back and see if there's a way I can clean it up a bit, or if anyone has any other suggestions? My model looks like this: Code: function editAnimal() So, when someone clicks "Edit", it brings up all the fields for this animal that they're editing....a foreach loop is not necessary for 1 item, right? I think this is a bit easier to read Code: Description: <?=$row->description?>
[eluser]louis w[/eluser]
You can access the first item like this: $row = $query->row(1); then $row->description Also, FYI this is not an array, it's an object. CI returns db results as an object. You need to convert it to an array if you want a true array.
[eluser]louis w[/eluser]
NP Check out this page, it outlines the different ways that you can retrieve database results. You can also do things like $query->first_row(); http://ellislab.com/codeigniter/user-gui...sults.html
[eluser]NateL[/eluser]
Awesome Thanks! So I read over that link and it looks like row() is what I need to use. Inside my model: Code: function editAnimal() Inside my controller: Code: function edit(){ and inside my view: Code: <?=$row->description?> Works great!! I'm starting to get the whole MVC architecture and I am really enjoying learning this technique.
[eluser]louis w[/eluser]
Looks good bro. Trust me you will really like MVC once you get it worked in to your everyday development architecture. It really helps you to create a flexible application. You may even want to rename $data['row'] to something like data or animal. So that in your view it's a little more obvious what that data set is. If in the future you want to do a second model call to look up an animal's region or something 'row' would make it hard to know which db row it is.
[eluser]NateL[/eluser]
Thanks again Louis. I just changed it to $data['animal'] = $this->animal_model->editAnimal(); and it works like a charm and looks much better ![]() <?=$animal->description?> super simple to understand |
Welcome Guest, Not a member yet? Register Sign In |