Kenan
Kenan

Reputation: 5

Sum column values with Codeigniter activerecord

SQL:

table name "videos"

column name "views"

I want to count all views and showing in User Page.

Example:

Result SQL:

-- views -- 3239

2918

2345

1928

32329


total views: 42759

Upvotes: 0

Views: 322

Answers (2)

sauhardnc
sauhardnc

Reputation: 1961

I've written a code which worked for me, I've explained the code wherever necessary. See if it helps you.

$query = $this->db->select_sum('views')->get('videos')->result();  // gets the sum of data in views column.

$totalViews = $query[0]->views;  // the array returned contains the sum in key {0}

echo $totalViews;  // echo or return the output -- your logic

Upvotes: 1

fraggley
fraggley

Reputation: 1285

You can pull the data from the database then use the array_sum() function. For example:

$builder = $db->table('mytable');
$query = $builder->get()->getResultArray();

$totalViews = array_sum($query['views']);

echo $totalViews;

Upvotes: 0

Related Questions