Skip to content
CODE THE PIXEL
CakePHP

CakePHP 4 Sum column value

Asyraf Wahi Anuar Updated 1 min read

This tutorial is a very short one. How to sum the value from a column in a table? Let say you’ve table stocks [id, product, brand, quantity]. To sum the quantity value, you can apply the following code to your controller.

This tutorial may be outdated

It was last reviewed 4 years ago. Some steps may differ in newer versions.

Tech stack

  • CakePHP 4.x

This tutorial is a very short one. How to sum the value from a column in a table? Let say you’ve table stocks [id, product, brand, quantity]. To sum the quantity value, you can apply the following code to your controller.

PHP
public function index()
{
    $stocks = $this->paginate($this->Stocks);
    //Count quantity
    $total_quantity = $this->Stocks->find();
    $count_quantity =$total_quantity->select(['sum' => $total_quantity->func()->sum('Stocks.quantity')])->first();
    $sum_quantity = $count_quantity->sum;

    $this->set(compact('stocks','sum_quantity'));
}

You can print the result using the following code in your view.

PHP
<?= $sum_quantity; ?>

That’s all. Happy coding :)

Did this tutorial help?

214 readers found this helpful

Comments

No comments yet. Questions about this tutorial are welcome here: the answer helps the next reader too.

Leave a comment

Markdown works: `code`, ``` blocks, **bold**, links.

First comments are reviewed before they appear.

CakePHP

CakePHP 4 Print Increment Number With Every Table Row

Increment number in every table row is very useful in some web application projects. This tutorial will show how to set a maximum limit of rows per page with an incrementing number in every row.

1 min read

CakePHP

CakePHP 4 Find, Sort & Count

This tutorial will show how to count registered records in your database using CakePHP 4 method. Basically, the process is to find the records based on the condition and count.

7 min read