0

I'm trying to pass an array to a view from a controller but I can't and I don't know why.

I have a model, a controller and a view.

The model:

<?php

class Modelo_bd extends CI_Model
{
    public function datos()
    {
        $cnb=$this->db->query("SELECT * from anuncios");
        return $cnb->result();  
    }
} 

?>

The controller:

if($this->modelo_usuarios->puede_entrar($usr)) 
{
   $this->load->model("modelo_bd");
   $cbd=$this->modelo_bd->datos();
   $this->load->view('datos',$cbd);

   return true;
}

The view:

<?php
echo $cbd->titulo_a;
echo $cbd->contenido;
?>

The error is in the view.

A PHP Error was encountered
Severity: Notice
Message: Undefined variable: cbd

A PHP Error was encountered
Severity: Notice
Message: Trying to get property of non-object

Why $cbd variable isn't recognized in the view if it is an array? How can I fix it?

Thanks.

4

3 回答 3

1

控制器中:

if($this->modelo_usuarios->puede_entrar($usr)) 
{
   $this->load->model("modelo_bd");
   $cbd=$this->modelo_bd->datos();
   $this->load->view('datos', array('cbd' => $cbd);       
   return true;
}

第二个参数应该是数组。

您可以在模型中使用:

public function datos()
{
    return $this->db->query("SELECT * from anuncios");
}

在视图中:

<?php
foreach ($cdb->result() as $item) {
  echo $item->titulo_a;
  echo $item->contenido;
}
?>
于 2013-02-26T12:08:49.620 回答
0

Shouldn't you rather do:

The controller:

if($this->modelo_usuarios->puede_entrar($usr)) 
{
   $this->load->model("modelo_bd");
   $data['cbd']=$this->modelo_bd->datos();
   $this->load->view('datos',$data);

       return true;
}

The view:

<?php
   foreach($cbd as $key => $row){
   echo $row->titulo_a;
   echo $row->contenido;
}

?>

I think this works better, your choice.

于 2013-02-26T16:29:37.180 回答
0

你应该这样做

if($this->modelo_usuarios->puede_entrar($usr)) 
{
   $this->load->model("modelo_bd");
   $data['cbd'] =   $this->modelo_bd->datos();
   $this->load->view('datos',$data);
}
于 2013-02-26T12:43:20.240 回答