Mehdi Raash
Mehdi Raash

Reputation: 8985

Getting data from model to controller

I do have a question : I cannot pass the data from model to controller You can see some of my codes, please help me. It does not work!

this is my model "mymodel.php"

 ....

$query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
    if($query){
    foreach ($query->result() as $row);
    }
    $t = "EXAMPLE/{$row->code}";
    function wandad() {
        return $t;
    }
.....

and this is my controller mycont.php

 ...
 $this->load->model('mymodel');

$data['new'] = $this->Mymodel->wandad();
$this->load->view('myview',$data);
 ...

and this is my view myview.php

 ....
 echo $new; 
 .....

Upvotes: 0

Views: 142

Answers (4)

GautamD31
GautamD31

Reputation: 28763

There is a small mistake in your code @Ernesto.that is

foreach ($query->result() as $row){
      $t. = "EXAMPLE/{$row->code}".'<br>';
   }

but your code was simply nice

Upvotes: 0

Ernesto Codeigniter
Ernesto Codeigniter

Reputation: 71

Clearly you The model is not written properly and to corrent this simple do this

1.) I put a default value on $t

2.) I put the query >> loop on the inside function

wandad

so it can be executed once called from controller

function wandad() {
    $query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1");
    $t = "";
    if($query){

       foreach ($query->result() as $row){
          $t = "EXAMPLE/{$row->code}".'<br>';
       }
     }

    return $t;
    }

Upvotes: 1

Wim Mostmans
Wim Mostmans

Reputation: 3601

@Touki his foreach actually does something. It will set the variable $row with the last row that is returned from the query. Not the best way to do it ... But it's a way. Better would be to use a limit in the query.

Upvotes: 0

Touki
Touki

Reputation: 7525

Here are several issues into your model

  • Your Foreach function doesn't do anything
  • $t is not in the same namespace than wandad()
  • Function wandad is not defined into your model class

I'm not sure of what you wanna get with wandad() function but here's a pattern.

function yourFunction()
{
    /* This will return the full query as an array */
    $query = $this->db->query("SELECT * FROM `rand` WHERE `used` = 0 LIMIT 0, 1")->result_array();
    /* Store variable in the same class */
    $this->t = "EXAMPLE/".$query[0]['code'];
/* Close yourFunction() */
}
public function wandad() {
    return $this->t;
}

Then into your controller, do that instead :

$this->load->model('mymodel');
$this->mymodel->yourFunction();
$data['new'] = $this->mymodel->wandad();
$this->load->view('myview',$data);

Upvotes: 1

Related Questions