1

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()

Dharman
  • 30,962
  • 25
  • 85
  • 135
Mani
  • 127
  • 1
  • 2
  • 7

3 Answers3

3

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();

Anshu Sharma
  • 162
  • 13
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()
Devsi Odedra
  • 5,244
  • 1
  • 23
  • 37
1

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;
Bluetree
  • 1,324
  • 2
  • 8
  • 25