在CodeIgniter中使用聚合函数SUM()

问题描述 投票:0回答:1

型号

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class transaction extends CI_Model{

    public function  mytransaction(){
        $this->load->database();
        $query = $this->db->get('transaction');
        return $query->result();
    }

    public function mySum(){
        $this->db->select("SUM(total) AS MySum");
        $this->db->from("transaction");
        return $query1->row();
    }
}

控制器

class Invoice extends CI_Controller{
    public function index(){
        $this->load->Model('transaction');
        $data1['query'] =  $this->transaction->mytransaction();
        $this->load->view('transactionview', $data1);
    }
}

查看

  <table width="600px" border="1px" style="margin:40px 300px;">
        <tr>
            <td>Sno.</td>
            <td>Product Code</td>
            <td>Name</td>
            <td>Quantity</td>
            <td>Rate</td>
            <td>Total</td>
        </tr>


    <?php foreach($query as $row){?>
    <tr>
        <td><?php echo $row->transaction_id;?></td>
        <td><?php echo $row->code;?></td>
        <td><?php echo $row->name;?></td>
        <td><?php echo $row->quantity;?></td>
        <td><?php echo $row->rate;?></td>
        <td><?php echo $row->total;?></td>
    </tr>

    <?php }?>

    <tr>
        <td colspan=4>Subtotal</td>
        <td colspan=2>?</td>
    </tr>

    <tr>
        <td colspan=4>Grand Total</td>
        <td colspan=2>?</td>
    </tr>
    </table>

我正在尝试将聚合函数与 Codeigniter 一起使用。为此,我想编写一个查询,对表的所有总计列进行求和,以便我可以将其回显到表的总计字段。为此,我如何将模型中的总和值传递到视图,以便我可以回显我的表中的总和值?

php mysql model-view-controller aggregate-functions codeigniter-2
1个回答
0
投票

型号功能:-

public function mySum(){
        $this->db->select("SUM(total) AS MySum");
        $this->db->from("transaction");
        $query1 = $this->db->get();
        if($query1->num_rows() > 0)
        { 
         $res = $query1->row_array();
         return $res['MySum'];
        }
       return 0.00;
    }

在控制器中调用模型函数:-

 // set grand total here
    $data1['g_total'] =  $this->transaction->mySum();

进入视图:-

    <tr>
        <td colspan=4>Grand Total</td>
        <td colspan=2><?php echo $g_total;?></td>
    </tr>
© www.soinside.com 2019 - 2024. All rights reserved.