Undefined variable in CodeIgniter
I am learning CodeIgniter and trying to pass an array to the View through my controller and when I call that array in the view it is presented to me as undefined.
This is my controller:
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Consulta extends CI_Controller {
public function index() {
$this->load->view("index");
}
public function listar_consultas() {
$this->load->view("listar");
}
public function salvar_consulta() {
$this->load->model("model_marcar_consulta");
if ($this->model_marcar_consulta->salvar_dados()) {
$this->load->view("sucesso");
} else {
$this->load->view("erro");
}
}
public function listando_consultas() {
$this->load->model("model_marcar_consulta");
$consulta = $this->model_marcar_consulta->retorna_lista_consulta();
$variaveis["consulta"] = $consulta;
$this->load->view("listar", $variaveis);
}
}
?>
And that's My View:
<table border="1">
<tr>
<td>Id</td>
<td>Especialidade</td>
<td>Data de Marcação</td>
<td>Horario de Marcação</td>
<td>Observação</td>
<td>Data de públicação</td>
</tr>
<?php foreach($consulta -> result() as $linha): ?>
<tr>
<td><?php echo $linha->id ?></td>
</tr>
<?php endforeach; ?>
</table>
I'm not really understanding this error:
A PHP Error was encountered
Severity: Notice
Message: Undefined variable: query
Filename: views/list.php
Line Number: 21
Fatal error: Call to a member function result () on a non-object in C:\Program Files(x86)\EasyPHP-5.3.8.0\www\mark_consult\application\views \ list.php on line 21
1 answers
Fatal error: Call to a member function result () on a non-object in C:\Program Files(x86)\EasyPHP-5.3.8.0\www\mark_consult\application\views \ list.php on line 21
In your View you use $consulta-> result()
, but the error reports that $consulta
is not an object. Apparently your model is returning an array with the result of the operation-com $query->result()
, and not the DB instance.
1) if your model is running the query with $this->db->get()->result()
, Your loop should reference a object:
<?php foreach($consulta as $linha): ?>
<tr>
<td><?php echo $linha->id ?></td>
</tr>
<?php endforeach; ?>
2) to use the result as an array, use $this->db->get()->result_array()
<?php foreach($consulta as $linha): ?>
<tr>
<td><?php echo $linha['id'] ?></td>
</tr>
<?php endforeach; ?>
more examples in the DOC from Codeigniter on results of DB operations.