CodeIngniter counting rows and displaying in View?

0

I want to count and display a database field.

Database: nbkg

Table: chamados

Model: chamados_model.php

<?php

class dashboard_model extends CI_Model{

    public function lista($chamados)
    {

    $query = $this->db->query('SELECT * FROM chamados');

    echo $query->num_rows();       

    }

}

Controller: Dashboard.php

    <?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Dashboard extends CI_Controller {

    public function index() {
        $this->load->view('dashboard.php');
        $this->load->model("dashboard_model");
        $this->load->database();
        $this->load->helper('url');
    }
}

View: dashboard.php

<?php echo $query ?>

Error: can not find variable Query :

  

A PHP Error was encountered >   Severity: Notice >   Message: Undefined variable: query >   Filename: views / dashboard.php

     

Line Number: 1

     

Backtrace:

     

File: /Applications/MAMP/htdocs/nbkg/application/views/dashboard.php   Line: 1 Function: _error_handler

     

File:   /Applications/MAMP/htdocs/nbkg/application/controllers/Dashboard.php   Line: 8 Function: view

     

File: /Applications/MAMP/htdocs/nbkg/index.php Line: 315 Function:   require_once

    
asked by anonymous 27.03.2017 / 13:14

1 answer

3

Model

<?php
class dashboard_model extends CI_Model
{
    public function __construct()
    {
        parent::__construct();
    }

    public function lista()
    {
        $query = $this->db->query('SELECT * FROM chamados');
        # se vai usar o valor em outro lugar, então pense que o mesmo será um retorno
        return (int) $query->num_rows();       
    }
}

Controller

<?php 
class Dashboard extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();

        # cria instancia da library
        $this->load->library('database');

        # cria instancia do helper
        $this->load->helper('url');
    } 


    public function index()
    {
        # cria instancia do model
        $this->load->model("dashboard_model");

        # executa sua função dentro da model e recupera o valor
        $lista = $this->dashboard_model->lista();

        # chama a view (não precisa do .php)
        # o array dentro da função da view, passa as chaves para a view e os transforma em variaveis (extract)
        $this->load->view('dashboard', 
            array(
                 'query' => $lista
            )
        );
    }
}
    
27.03.2017 / 13:47