Playing Controller Info for View CI3

Asked

Viewed 88 times

1

I’m working with Codeigniter3 in the MVC model and I’ve been having problems for a long time, I’m slowly solving some problems here and there and I’m almost getting to the point.

I’m making a query in random order in DB by model:

public function get_rand(){

$frase = $this->db->query("SELECT frase FROM frases ORDER BY RAND() LIMIT 1");
if($frase->num_rows() > 0):
    return $frase->result();
else:
    return NULL;
endif;

}

and pulling inside the Controller:

public function index(){
    if($frase = $this->randfrase->get_rand(1)):
            foreach ($frase as $linha) :
                    echo $linha->frase;
            endforeach;
    else:
            return NULL;
    endif;

}

I mounted it so I could see by URL if the Randomica selection was working. The Model part is 100%, now I wanted to know how I can instead of printa, send the info to a view aside of my system. Someone might be able to help. In case this information should appear in an aside that is standard for the entire site. I tried to put this controller code right in the view but it always error:

PHP Error was encountered

Severity: Notice

Message: Undefined Property: Ci_loader::$randfrase

Filename: views/aside.php

Line Number: 3

Backtrace:

File: C: xampp htdocs codeigniter site application views aside.php Line: 3 Function: _error_handler

File: C: xampp htdocs codeigniter site application views home.php Line: 27 Function: view

File: C: xampp htdocs codeigniter site application controllers pagina.php Line: 14 Function: view

File: C: xampp htdocs codeigniter site index.php Line: 315 Function: require_once

Fatal error: Call to a Member Function get_rand() on a non-object in C: xampp htdocs codeigniter site application views aside.php on line 3 PHP Error was encountered

Severity: Error

Message: Call to a Member Function get_rand() on a non-object

Filename: views/aside.php

Line Number: 3

Backtrace:

1 answer

0

I never used that aside, but it seems to be a normal view after all..

well.. what I think what I understood was that you are not calling the model correctly, so see if it helps you in something

Suppose your model is called Randfrase and your aside is called aside only.

so the way I see it, it has to look like this on your controller:

public Function index(){

if($frase = $this->randfrase->get_rand(1)){
    //carrega a model
    $this->load->model('randfrase'); 

    //utiliza o método da model
    $dados['frase'] = $this->randfrase->get_rand(); 

    //sua aside seria uma view no meu exemplo que recebe o array
    $this->load->view('aside',$dados);
}            

}

Now in your view aside you do more or less what you tried to do before like this:

foreach ($frase as $linha) :
    echo $linha->frase;
endforeach;

I hope that’s more or less what you need.. Good luck.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.