Welcome Guest, Not a member yet? Register   Sign In
export model results to variables
#1

[eluser]nigelb[/eluser]
I have written the following piece of code to convert the results from a model (array) to php variables

Code:
$this->load->model('Home');
$home=$this->Home->getHome();

foreach ($home as $homearr) {
    extract($homearr);
}

$data["title"]=$title;
$data["content"]=$content;

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

Is there a better way to do this as it seems a bit long winded to me
#2

[eluser]nirbhab[/eluser]
When you are going to work on large php scripts/projects than you will need the model, to make your code more cleaner and understandable (to you and to others-might be debugged by other at some times).
There are inline php coded sites also, but we follow MVC, so that our code is well formated, matches some or the other standards,e.i. accepted universally.

And according to me the flow of your above code is gud to begin learning CI.
#3

[eluser]nigelb[/eluser]
my question was, is there a better way to return results from a Model into a view.
#4

[eluser]Phil Sturgeon[/eluser]
Yes, we use an array over extraced variables so we can pass chunks of data into and out of models with ease. You code does not need that foreach loop and it doesnt need to be extracted.

Code:
$this->load->model('Home');
$data = $this->Home->getHome();

$this->load->view('display/home', $data);
#5

[eluser]nigelb[/eluser]
I know I can do that, but what I was trying to do was just send to a view information that i know I want, instead of processing an array on the view page (building a small CMS system). Is it wrong to do this?
#6

[eluser]Phil Sturgeon[/eluser]
If you only want to use certain bits from the array, then take out the certain bits and put them in a new array.

Code:
$this->load->model('Home');
$home = $this->Home->getHome();

$data['title']=$home['title'];
$data['content']=$home['content'];

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

Or you can add in a SELECT parameter to your get function.
#7

[eluser]nigelb[/eluser]
there lies my problem instead of returning an one array, I am getting an array in an array.

I am using return $query->first_row(); in the model, is there something better to use?
#8

[eluser]Phil Sturgeon[/eluser]
Indeed, as the documentation suggests you can use $query->row_array() for the single array or you can use $query->result_array() to get the multidimentional array.




Theme © iAndrew 2016 - Forum software by © MyBB