Variable undefined in CodeIgniter

0

I'm 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 this is 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 really not understanding this error:

  

A PHP Error was encountered

     

Severity: Notice

     

Message: Undefined variable: query

     

Filename: views / listar.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 \ tag_query \ application \ views \ listar.php on line 21

    
asked by anonymous 17.09.2014 / 01:32

1 answer

1
  

Fatal error: Call to a member function result on a non-object in C: \ Program Files (x86) \ EasyPHP-5.3.8.0 \ www \ tag_query \ application \ views \ listar.php on line 21

In your view you use $consulta-> result() , but the error informs you that $consulta is not an object. Apparently your model is returning an array with the result of the operation - with $query->result() , not the DB instance.

1) If your model is executing the query with $this->db->get()->result() , your loop should reference object:

<?php foreach($consulta as $linha): ?>
   <tr>
       <td><?php echo $linha->id ?></td>
   </tr>
<?php endforeach; ?>

2) To use the result in array form, use $this->db->get()->result_array()

<?php foreach($consulta as $linha): ?>
   <tr>
       <td><?php echo $linha['id'] ?></td>
   </tr>
<?php endforeach; ?>

More examples on Codeigniter DOC on results of DB operations.

    
17.09.2014 / 04:02