phpcodeigniterselectactiverecordsum

Implement SELECT SUM() query using Codeigniter select_sum() active record method and return the value


I needed to add up the column values of all the rows for a result. I am using the select_sum() in my code and using its second parameter to assign the column alias, but it is returning an array.

My model method:

function Dues_Paid_Tot($date)
{
    $query = $this->db->select_sum('Dues_Paid', 'Dues_Paid_Tot');
    $query = $this->db->get('Membership');
    return $query->result();
}

Here is the controller

function Fiscal2()
{
    $date = $this->input->post('Select_Date');
    if($query = $this->report_model->fiscal_list($date))
    {
        $data['records'] = $query;
    }
    $data['date'] = $this->input->post('Select_Date');
    $data['Dues_Paid_Tot'] = $this->report_model->Dues_Paid_Tot($date);
    $data['main_content'] = 'report_fiscal_view';
    $this->load->view('includes/template', $data);
}

And this is the pertinent code for the view:

<?php echo $Dues_Paid_Tot; ?>

The problem is, instead of showing a summation of all the entries in the column Dues_Paid, I get "Array" in my view.

Where am I going wrong?


Solution

  • It is still a query so you still have to process the result, try changing your model to this...

    function Dues_Paid_Tot($date)
    {
        $query = $this->db->select_sum('Dues_Paid', 'Dues_Paid_Tot');
        $query = $this->db->get('Membership');
        $result = $query->result();
    
        return $result[0]->Dues_Paid_Tot;
    }