Search code examples
phpcodeigniteractiverecord

Save the total sum in my table (codeigniter)


Newbie at codeigniter here. how can I save my total amount in my table per user? The only thing I did is to sum it and show it on my view. My target is to save the total commission on my "agent_commission" table". I have provided a screenshot of my target for better visualization. Thank you in advance. Any help will be appreciated.

enter image description here

Views:

<?php $formattedNum = number_format($commCurrentBalance, 2);
                            echo $formattedNum;
                            ?

Controller:

public function commi()
    {
        $data['activeNav'] = "";
        $data['subnav'] = "commissions";
        $this->header($data);
        $this->nav();
        $data['currentPoints']=$this->session->userdata('currentPoints');
        $data['result'] = $this->commissions->get1();
        $data['commCurrentBalance']=$this->load->commissions->gettotalcommi(); //getting sum of amount
        $this->load->view('comm_view', $data);
        
        $this->footer();
    }

Model:

function gettotalcommi(){
        $reqcommi= $this->session->userdata('uid');
        
        $this->db->select_sum('amount');
        $this->db->where('commTo',$reqcommi);
        $result = $this->db->get('agent_commission_history')->row();
        
        return $result->amount;
    }

Solution

  • I'm not sure if it will work but please try

    $db->select_sum('amount');
    $db->where('commTo',$param);
    $aq = $db->get_compiled_select('agent_commission_history');
    
    $db->set('commCurrentBalance',"($aq)",false);
    $db->where('commTo',$param2);
    $db->update('agent_commission');
    

    This is the Codeigniter equivalent of the query I posted earlier:

    UPDATE agent_commission 
    SET commCurrentBalance = ( SELECT SUM(amount) FROM agent_commission_history WHERE commTo = ?) 
    WHERE commTo = ?