Search code examples
phpcodeigniter

How to Show counted data to Html using php codeigniter


so here is my model codes:

public function GetId()
{
    $this->db->select('count(*) as total');
    $this->db->from($this->table);
    $this->db->where('dibaca', null);
    $query = $this->db->get();
    return $query->result_array();
}

and this is my code in html:

<?= $DataId['total']; ?>

i already call the function to my controller as DataId, and i get error that Undefined array key "total"

can you guys tell me what is wrong in it?


Solution

  • Some untested advice:

    Your model can be refined to:

    public function countNullDibaca(): int
    {
        return $this->db
            ->where("dibaca", null)
            ->count_all_results($this->table);
    }
    

    Your controller should call for the model data and pass it to the view.

    public function myController(): void
    {
        $this->load->model('my_model', 'MyModel');
        $this->load->view(
            'my_view',
            ['total' => $this->MyModel->countNullDibaca()]
        );
    }
    

    Finally, your view can access the variable that associates with the first-level key in the passed in array.

    <?= $total; ?>
    

    Here is a related post which speaks on passing data from the controller to the view.