how to get sum of a column with codeigniter query [duplicate]

馋奶兔 提交于 2021-02-17 05:54:08

问题


I am trying to get sum of a column values in mysql table with the codeigniter query as

$this->db
     ->query("Select SUM(tb1.amount) from table1 tb1 inner join table2 tb2 on tb2.Id=tb1.Id Where tb2.Status='1'")
     ->result()

it give me error as array to string conversion I need just a number such count(amount) returns number of rows with num_row()


回答1:


use as => $data['total']

$data = $this->db
     ->query("Select SUM(tb1.amount) as total from table1 tb1 inner join table2 tb2 on tb2.Id=tb1.Id Where tb2.Status='1'")
     ->row_array()



回答2:


You can use select_sum() function of codeigniter. Try the following code-

$query = $this->db->select_sum("tb1.amount")
                  ->from("table1 as tb1")
                  ->join("table2 as tb2","tb1.id = tb2.id") 
                  ->where("tb2.status",1)
                  ->get();
$query = $query->result();

OR

$query = $this->db->query('SELECT sum(tb1.amount) FROM table1 as tb1 join table2 as tb2 on tb1.id = tb2.id where tb1.status = 1'); $query = $query->result_array();




回答3:


Use row() instead of result if you want to get a single row.

$data = $this->db
     ->query("Select SUM(tb1.amount) as total from table1 tb1 inner join table2 tb2 on tb2.Id=tb1.Id Where tb2.Status='1'")
     ->row()

To get the data.

echo $data->total;


来源:https://stackoverflow.com/questions/59223909/how-to-get-sum-of-a-column-with-codeigniter-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!