Codeigniter:字段中记录的总和

时间:2014-11-23 09:41:58

标签: php mysql codeigniter activerecord sum

我从mysql数据库中获取一些信息,并使用以下脚本显示它(我正在使用Codeigniter)。

模型

    public function sum($field, $table, $userfield, $username)
    {
        return $this->db->query("SELECT SUM($field) FROM $table WHERE $userfield = '$username'");
    }

控制器

    public function save(){
        $data = array(
        'sum_simpan' => $this->user_m->sum('besar_simpanan', 'simpanan', 'id', $this->session->userdata('username'))->result()
    ); }

查看

    <div class="info-a">
        <p>Total Simpanan Anda</p>
        <h3><?php  
           foreach ($sum_simpan as $row) {
            echo $row->besar_simpanan;
           }
        ?>
            </h3>
    </div>

我想要做的是对字段的内容求和,并在视图中显示它。 但是我收到了错误

A PHP Error was encountered Severity: Notice

Message: Undefined property: stdClass::$besar_simpanan

Filename: anggota/simpanan.php

Line Number: 14


请您告诉我该怎么做。

提前致谢:)

1 个答案:

答案 0 :(得分:0)

像这样改变你的模型

public function sum($field, $table, $userfield, $username)
    {
        return $this->db->query("SELECT SUM($field) as total FROM $table WHERE $userfield = '$username'");
    }

也是视图

<h3>
<?php  
    foreach ($sum_simpan as $row) {
            echo $row->total;
     }
?>
</h3>