Current Location: Home> Latest Articles> Yii Framework Data Statistics: Daily, Monthly, Yearly, and Custom Time Period Statistics

Yii Framework Data Statistics: Daily, Monthly, Yearly, and Custom Time Period Statistics

gitbox 2025-07-18

Introduction

Yii framework is a high-performance development framework focused on quickly building modern web applications. It offers a rich set of features and components, allowing developers to efficiently fulfill various requirements. In this article, we will discuss how to implement data statistics by day, month, year, and custom time periods in Yii framework.

Daily Statistics

Before implementing daily statistics, we need a data table to store the data that we wish to count. Here is an example of the data table:

CREATE TABLE `statistics` (
    `id` int(11) NOT NULL AUTO_INCREMENT,
    `date` date NOT NULL,
    `count` int(11) NOT NULL,
    PRIMARY KEY (`id`)
);

Next, we need to create a data model in Yii framework to operate this table. You can use Yii's Gii code generator to automatically generate the model code.

<span class="fun">yii gii/model --tableName=statistics --modelClass=Statistics</span>

The generated Statistics model will help simplify our operations on the data table.

To count data daily, we can use the following code:

$today = date('Y-m-d');
$count = Statistics::find()
    ->where(['date' => $today])
    ->sum('count');

The above code will query today's data and calculate the total count.

Monthly and Yearly Statistics

To implement monthly and yearly statistics, we use a similar method to daily statistics with slight modifications. Here is the code example for monthly statistics:

$thisMonth = date('Y-m');
$count = Statistics::find()
    ->where(['like', 'date', $thisMonth])
    ->sum('count');

By using the like operator, we can filter data that includes the current month.

Similarly, here is the code example for yearly statistics:

$thisYear = date('Y');
$count = Statistics::find()
    ->where(['like', 'date', $thisYear])
    ->sum('count');

Custom Time Period Statistics

If you need to perform statistics for a custom time period, you can do so by passing in the start and end dates. Here is an example of the code:

$startDate = '2022-01-01';
$endDate = '2022-12-31';
$count = Statistics::find()
    ->where(['between', 'date', $startDate, $endDate])
    ->sum('count');

The above code will calculate the data from January 1, 2022, to December 31, 2022.

Conclusion

Using Yii framework to implement data statistics by day, month, year, and custom time periods is relatively straightforward. By leveraging Yii's query builder, we can easily filter and calculate the required data.

This concludes the detailed explanation of implementing daily, monthly, yearly, and custom time period statistics in Yii framework. I hope this article is helpful to you.