Codeingniter counting lines and displaying on View?

Asked

Viewed 232 times

1

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: does not find the variable Query:

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

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
            )
        );
    }
}
  • now giving error An Error Was Encountered Unable to load the requested class: Database

  • Retire $this->load->library('database'); and add 'database' in the array of the archive application/config/autoload.php in the key $autoload['libraries'].

  • And in the view I call $list. correct?

  • No, keep it intact if you followed my example. The variable is called $query (see the key to array that it turns into variables).

  • Done!! Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.